Back

Copying a Text File, Then Replacing Text Within the File using C#

The following bit of code enables you to create a copy of an existing file and then replace a string of text within that file with whatever you want.  This might be useful for instance if you have a template which you need to recreate each time and then replace text within the template with whatever text you want.

In this example file1.txt is the template file and file2.txt is what it will be copied to.  String1 is the text you want to find in that file and replace it with String2.


StreamReader sr = new StreamReader("c:\file1.txt";
StreamWriter sw = new StreamWriter("c:\file2.txt";
string inputline, outputline;

 

while((inputline = sr.ReadLine()) != null)
{
outputline = inputline.Replace("String1", "String2");
sw.WriteLine(outputline);
}

 

sr.Close();
sw.Close();

 

Make sure you add

using System.Text;

to the top of your code behind file.

Back


Make a Comment on this Article

Your Name:
Comment: