c# overwrite text in text file
How to Overwrite Text in a Text File using C#
If you're working on a C# project that requires you to modify the content of a text file, you may need to overwrite the existing text with new data. Here are a few ways to accomplish this:
Method 1: Using FileStream and StreamWriter
This method involves creating a FileStream object and a StreamWriter object to write to the file. Here's how you can do it:
string filePath = "C:\\example.txt";
string contentToWrite = "This is new content.";
using (FileStream fileStream = new FileStream(filePath, FileMode.Truncate))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
streamWriter.Write(contentToWrite);
}
}
In this example, we first define the path to the file we want to modify and the new content we want to write. Then we use a FileStream object with the Truncate FileMode to overwrite the entire contents of the file. Finally, we use a StreamWriter object to write the new content to the file.
Method 2: Using File.WriteAllLines
If you want to replace all the lines in a text file with new content, you can use the File.WriteAllLines method. Here's an example:
string filePath = "C:\\example.txt";
string[] newContent = { "This is line 1", "This is line 2", "This is line 3" };
File.WriteAllLines(filePath, newContent);
In this example, we define the path to the file we want to modify and an array of strings representing the new lines of content. Then we call the File.WriteAllLines method, which overwrites all the lines in the file with the new content.