Replace Text in File with C#: Easy Step-by-Step Tutorial
When working with text files in C#, it's often necessary to replace certain text within the file. This can be done easily with the use of the
StreamWriter classes in C#. In this tutorial, we will walk through the steps to replace text in a file using C#.
Step 1: Open the File
The first step is to open the file that we want to replace text in. We can do this by creating a new instance of the
StreamReader class and passing in the file path as a parameter.
StreamReader reader = new StreamReader("file.txt");
Step 2: Read the File
Once we have opened the file, we can read its contents using the
ReadToEnd() method of the
StreamReader class. We will store the contents of the file in a string variable.
string content = reader.ReadToEnd();
Step 3: Replace the Text
Now that we have the contents of the file stored in a string variable, we can replace the text that we want to replace using the
Replace() method. We will replace all occurrences of the text "old text" with the text "new text".
content = content.Replace("old text", "new text");
Step 4: Write the File
Once we have made the necessary replacements, we can write the updated contents back to the file using the
StreamWriter class. We will create a new instance of the
StreamWriter class and pass in the file path as a parameter. We will then call the
Write() method to write the updated contents to the file.
StreamWriter writer = new StreamWriter("file.txt"); writer.Write(content); writer.Close();
In this tutorial, we have learned how to replace text in a file using C#. By following these easy step-by-step instructions, you can easily replace text in any text file using C#.