Write to a file with C#
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
|
1 2 3 4 5 6 7 8 9 10 11 12 |
using System.IO; public class Example { public static void Main() { string path = @"C:\path\somefile.txt"; string text = @"Some Text"; File.WriteAllText(path, text); } } |
⮚ File.WriteAllLines() method
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\path\somefile.txt"; string multiLineText = @"Some Multiline Text"; File.WriteAllLines(path, multiLineText.Split(Environment.NewLine)); } } |
⮚ File.WriteAllBytes() method
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System.Text; using System.IO; public class Example { public static void Main() { string path = @"C:\path\somefile.txt"; string text = @"Some Text"; byte[] bytes = Encoding.ASCII.GetBytes(text); File.WriteAllBytes(path, bytes); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System.IO; public class Example { public static void Main() { string path = @"C:\path\somefile.txt"; string text = @"Some Text"; using (StreamWriter writer = new StreamWriter(path)) { writer.Write(text); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System.IO; using System.Text; public class Example { public static void Main() { string path = @"C:\path\somefile.txt"; string text = @"Some Text"; using (FileStream file = File.Create(path)) { byte[] bytes = Encoding.ASCII.GetBytes(text); file.Write(bytes, 0, bytes.Length); } } } |
That’s all about writing to a file with C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)