This post provides an overview of some of the available alternatives to writing text to a file in C#. The solution should create a new file if it doesn’t exist and truncate an existing file before writing.

1. Using File Class

The File class provides several static utility methods to write text to a file. The examples of each of these methods are covered below:

File.WriteAllText() method

Download Code

File.WriteAllLines() method

Download  Run Code

File.WriteAllBytes() method

Download Code

 
Note that the above-mentioned methods overwrite an existing file. To append text to a file, use either of AppendAllLines, AppendAllText, or AppendText() methods.

2. Using StreamWriter Class

StreamWriter class provides several methods for writing to a file. We can use its Write() method for writing a string to the stream.

The following example shows how to use the StreamWriter object to write data to a new file. The Dispose() method is called automatically to flush and closes the stream as the stream writer is declared and instantiated in a using statement.

Download Code

3. Using FileStream Class

The FileStream class provides several methods for writing to a file. We can use its Write() method for writing a block of bytes to the file stream. The following code example demonstrates its usage.

Download Code

That’s all about writing to a file with C#.