Summary: in this tutorial, you’ll learn various techniques to write text files in C# using the File
static methods and StreamWriter
class.
Writing all text into a text file
The
method creates a new file, writes the contents to it, and then closes the file:File.WriteAllText
()
public static void WriteAllText (string path, string? contents);
Code language: C# (cs)
If the file specified by the path exists, the WriteAllText()
method overwrites it. In other words, the contents of the existing file will be replaced by the contents.
The following program demonstrates how to use
method to write all text into a text file:File.WriteAllText
()
using static System.Console;
string path = @"C:\temp\readme.txt";
string contents = "Hello\nGoodbye";
File.WriteAllText(path, contents);
Code language: C# (cs)
The readme.txt
will look like the following:
Hello
Goodbye
Code language: C# (cs)
This program writes the string “Hello” and “Goodbye” to the readme.txt
file located in the “C:\temp” directory.
If the C:\temp directory does not exist, the WriteAllText()
method throws a DirectoryNotFoundException
.
For example, the following program attempts to write text to a file readme.txt
located in the C:\temp1
directory. Since the directory C:\temp1
doesn’t exist, the program shows a message provided by the DirectoryNotFoundException
object:
using static System.Console;
string path = @"C:\temp1\readme.txt";
string contents = "Hello\nGoodbye";
try
{
File.WriteAllText(path, contents);
}
catch (DirectoryNotFoundException e)
{
WriteLine(e.Message);
}
Code language: C# (cs)
Output:
Could not find a part of the path 'C:\temp1\readme.txt'.
Code language: C# (cs)
To check if the text file exists before writing the contents to it, you can use the
method like this:File.Exists
()
using static System.Console;
string path = @"C:\temp\readme.txt";
string contents = "Hello\nGoodbye";
if (!File.Exists(path))
{
File.WriteAllText(path, contents);
}
else
{
WriteLine($"The file {path} alrady exists");
}
Code language: C# (cs)
Output:
The file C:\temp\readme.txt alrady exists
Code language: C# (cs)
Writing one or more strings into a text file
To write one or more strings into a text file, you use the
method. The
()File.WriteAllLines
method creates a new file, writes one or more strings to the file, and then closes the file:
()File.WriteAllLines
public static void WriteAllLines (
string path,
string[] contents
);
Code language: C# (cs)
For example:
string path = @"C:\temp\readme.txt";
string[] lines = new[] {
"Hello",
"Hi",
"Hey"
};
File.WriteAllLines(path, lines);
Code language: C# (cs)
The readme.txt
file will look like this:
Hello
Hi
Hey
Code language: C# (cs)
Writing into a text file using StreamWriter
When you have a large amount of text data that you want to write into a text file in sequential order, you can use StreamWriter
. For example:
string path = @"C:\temp\readme.txt";
// in practice, the greetings is very big
string[] greetings = new[] { "Hello", "Hi", "Hey" };
var fs = new FileStream(path, FileMode.Open);
var stream = new StreamWriter(fs);
foreach (var greeting in greetings)
{
// write each line to the stream
stream.WriteLine(greeting);
}
Code language: C# (cs)
How it works.
First, define a string variable named “path” and assigns it the value of the file path C:\temp\readme.txt
where we want to write the text.
Next, create an array of strings named “greetings” that has three different strings – "Hello",
"Hi"
, and "Hey"
.
Then, create a FileStream
object named fs that open the file specified by the path with the mode FileMode
.Open.
After that, create a StreamWriter
object that writes text to the file using the FileStream
object.
Finally, iterate the greetings array and write each element into the file using the StreamWriter
object.
Writing into a text file asynchronously
To write data into a text file asynchronously, you can use the async
versions of the WriteAllText
and WriteAllLines()
methods:
public static Task WriteAllTextAsync (string path, string? contents, CancellationToken cancellationToken = default);
public static Task WriteAllLinesAsync (string path, IEnumerable<string> contents, CancellationToken cancellationToken = default);
Code language: C# (cs)
For example:
string path = @"C:\temp\readme.txt";
string[] greetings = new[] {
"Hello",
"Hi",
"Hey"
};
await File.WriteAllLinesAsync(path, greetings);
Code language: C# (cs)
In this example, we use the WriteAllLinesAsync()
method to asynchronously write the array of strings into a text file.
Note that we use the await
keyword to wait for the WriteAllLinesAsync()
method to complete.
Summary
- Use the
method to write all text into a text file.File.WriteAllText
() - Use the
method to write text data into a text file asynchronously.File.WriteAllTextAsync
() - Use the
method to write an array of strings into a text file.File.WriteAllLines
() - Use the
method to write an array of strings into a text file asynchronously.File.WriteAllLinesAsync
() - Use the
StreamWriter
to write a large amount of text into a text file.