Find and Replace for Multiline Text

Many of us would have used "Find and Replace" option available in our IDE and in many of the text editors. This functionality finds a single line of text given and replaces with the given text in the current document as well as in the files under a given folder. But how would you find and replace a multiline text? In this article I have tried to explain that.

FindnReplace.JPG

The project included in this article has a simple file reading operation. For the beginners first let me explain how to read files. You can skip this section if you are familiar with file operations.

File Operations

The first step is to include the System.IO namespace in the using directive.

using System.IO;


System.IO namespace has DirectoryInfo class which is used for typical operations such as copying, moving, renaming, creating, deleting and enumerating through directories and sub-directories. Files under a specific directory can be found using this class.

The following statement instantiates DirectoryInfo class with a folder path from the text box.

DirectoryInfo DI= new DirectoryInfo(txtFolder.Text);

 

To get the file information we use the following statement.

 

foreach(FileInfo FI in DI.GetFiles())

 

The GetFiles method of the DirectoryInfo class, returns an array of FileInfo object. The FileInfo class like DirectoryInfo has operations for reading, copying, moving, renaming, creating and deleting files.

Now we use a StreamReader object to read the file.

StreamReader SR= new StreamReader(FI.OpenRead());

 

We use the following statement to read a line and assign it to a string variable.

 

s=SR.ReadLine();

 

Search Operation

We read each line and store it in a temporary variable appending a new line character ("\r\n") at the end of the line.

This will differentiate each line for searching multiline text.

temp=temp+s+"\r\n";

Now to search the string we use IndexOf() method in the temporary variable with the search text as parameter.

pos=temp.IndexOf(txtFind.Text);

The above statement returns the position of the search text.

We use a list box to record the number of files that matches the search text and the occurence of the first position.

Replace Operation

For the replace functionality, we use Replace() method in the temporary variable with search string and string to replace as arguments.

temp=temp.Replace(txtFind.Text,txtReplace.Text);

To reflect this change in the actual file, we need to write it to the file. So we use StreamWriter object to write to the file.

StreamWriter SW= new StreamWriter(FI.OpenWrite());
SW.Write(temp);
SW.Close();

 

Source code is included at the top section of this article. The code is self explanatory.

Thats all folks!!!

Up Next
    Ebook Download
    View all
    Learn
    View all