How to write to a text file (C# Programming Guide)

In this article, there are several examples showing various ways to write text to a file. The first two examples use static convenience methods on the System.IO.File class to write each element of any IEnumerable<string> and a string to a text file. The third example shows how to add text to a file when you have to process each line individually as you write to the file. In the first three examples, you overwrite all existing content in the file. The final example shows how to append text to an existing file.

These examples all write string literals to files. If you want to format text written to a file, use the Format method or C# string interpolation feature.

Write a collection of strings to a file

class WriteAllLines
{
    public static async Task ExampleAsync()
    {
        string[] lines =
        {
            "First line", "Second line", "Third line" 
        };

        await File.WriteAllLinesAsync("WriteLines.txt", lines);
    }
}

The preceding source code example:

  • Instantiates a string array with three values.

  • Awaits a call to File.WriteAllLinesAsync which:

    • Asynchronously creates a file name WriteLines.txt. If the file already exists, it is overwritten.
    • Writes the given lines to the file.
    • Closes the file, automatically flushing and disposing as needed.

Write one string to a file

class WriteAllText
{
    public static async Task ExampleAsync()
    {
        string text =
            "A class is the most powerful data type in C#. Like a structure, " +
            "a class defines the data and behavior of the data type. ";

        await File.WriteAllTextAsync("WriteText.txt", text);
    }
}

The preceding source code example:

  • Instantiates a string given the assigned string literal.

  • Awaits a call to File.WriteAllTextAsync which:

    • Asynchronously creates a file name WriteText.txt. If the file already exists, it is overwritten.
    • Writes the given text to the file.
    • Closes the file, automatically flushing and disposing as needed.

Write selected strings from an array to a file

class StreamWriterOne
{
    public static async Task ExampleAsync()
    {
        string[] lines = { "First line", "Second line", "Third line" };
        using StreamWriter file = new("WriteLines2.txt");

        foreach (string line in lines)
        {
            if (!line.Contains("Second"))
            {
                await file.WriteLineAsync(line);
            }
        }
    }
}

The preceding source code example:

Append text to an existing file

class StreamWriterTwo
{
    public static async Task ExampleAsync()
    {
        using StreamWriter file = new("WriteLines2.txt", append: true);
        await file.WriteLineAsync("Fourth line");
    }
}

The preceding source code example:

Exceptions

The following conditions may cause an exception:

There are additional conditions that may cause exceptions when working with the file system, it is best to program defensively.

See also