C# Write Text Files

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 File.WriteAllText() method creates a new file, writes the contents to it, and then closes the file:

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 File.WriteAllText() method to write all text into a text file:

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
GoodbyeCode 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 File.Exists() method like this:

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 existsCode 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 File.WriteAllLines() method. The File.WriteAllLines() method creates a new file, writes one or more strings to the file, and then closes the file:

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
HeyCode 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 File.WriteAllText() method to write all text into a text file.
  • Use the File.WriteAllTextAsync() method to write text data into a text file asynchronously.
  • Use the File.WriteAllLines() method to write an array of strings into a text file.
  • Use the File.WriteAllLinesAsync() method to write an array of strings into a text file asynchronously.
  • Use the StreamWriter to write a large amount of text into a text file.
Was this tutorial helpful ?