Skip to content
the poor coder

c# overwrite text in text file

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

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:

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC