In C#, we encounter various scenarios where we might need to overwrite an existing file. Whether to update the file or completely overwrite it, handling the overwrite efficiently is crucial to ensure data integrity and prevent data loss.

In this article, we will explore the various methods we can use to overwrite a file in C#.

To download the source code for this article, you can visit our GitHub repository.

Let’s get started.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Writing Plain Text to an Existing File

Let’s consider that we have an existing text file content.txt with the content:

Hello, World!

Now let’s create a simple class library project. We start by initializing a const string with some text that we will write to the file, as well as another one for the file path:

const string contentToWrite = "Hello, Code Maze!";
const string filePath = "content.txt";

File.WriteAllText() Method

The first method to overwrite an existing file is the File.WriteAllText() method where we pass the file path and content as arguments:

File.WriteAllText(filePath, contentToWrite);

Now we can use the File.ReadAllText() to read the content of the file:

File.ReadAllText(filePath); // Hello, Code Maze!

StreamWriter Class

We can also use the StreamWriter class to overwrite an existing file. The StreamWriter constructor accepts two arguments, filePath of type string and append of type boolean. When append is set to false, it will overwrite the content of the file. Otherwise, it will append it to the existing content.

Let’s start with the StreamWriter class with append set to false:

using var streamWriter = new StreamWriter(filePath, false);

Then we call the Write() method on the StreamWriter instance which accepts a string as an argument:

streamWriter.Write(contentToWrite);

After that, we can read the content of the file using the File.ReadAllText() method:

File.ReadAllText(filePath); // Hello, Code Maze!

Now, let’s change the append argument to true:

using var streamWriter = new StreamWriter(filePath, true);
streamWriter.Write(contentToWrite);

Finally, we can check the content of the file using the File.ReadAllText() method:

File.ReadAllText(filePath); // Hello, World!Hello, Code Maze!

Writing Bytes to an Existing File

The previous examples demonstrated how we can write plain text to an existing file. In other scenarios, we might need to write bytes into the file such as images, videos, audio, etc.

First, let’s start by initializing a byte array, as well as a const string for the file path:

var fileContent = new byte[] {56, 71, 21, 17, 32};
const string filePath = "content.txt";

File.WriteAllBytes() Method

One of the ways to overwrite an existing file with bytes is by using the File.WriteAllBytes() method:

File.WriteAllBytes(filePath, fileContent);

Now we can use the File.ReadAllBytes() method to read the byte content of the file and we can see that the content of the file has changed:

File.ReadAllBytes(filePath); // {56, 71, 21, 17, 32}

FileStream Class

Another way to overwrite an existing file is to use FileStream with mode set to FileMode.Create and access set to FileAccess.Write:

using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);

Then we can call the Write() method on the FileStream instance, which accepts a byte array as the primary argument:

fileStream.Write(fileContent, 0, fileContent.Length);

Using the File.ReadAllBytes(), we can see that the content of the file has changed as expected:

File.ReadAllBytes(filePath); // {56, 71, 21, 17, 32}

File.Open() Method

Another method we can use to overwrite an existing file is the static File.Open() method with mode set to FileMode.Create:

using var stream = File.Open(filePath, FileMode.Create);

This method will return a FileStream instance. We can call the Write() method on the FileStream, passing the content byte array as the primary argument:

stream.Write(fileContent, 0, fileContent.Length);

Now we can use the File.ReadAllBytes() method to confirm that the content of the file has been overwritten:

File.ReadAllBytes(filePath); // {56, 71, 21, 17, 32}

Conclusion

C# offers several versatile approaches to overwrite existing files, catering to both text and binary data manipulation. However, caution is paramount to avoid data loss or unintended outcomes, warranting proper error handling and adherence to best practices.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!