Appending a text file in C#

Here are the basic ways of appending text to an existing file. Each of these will create a new file if the file does not already exist. Each are useful in different situations.

All three of these have an equivalent Async version as well.

/// <summary>
/// When you have a single string:
/// </summary>
void SingleString()
{
    string fileContents = $"{DateTime.Now:HHmmss}\n";
    File.AppendAllText(FULL_FILE_NAME, fileContents);
}

/// <summary>
/// When you have a collection of lines:
/// </summary>
void Lines()
{
    string[] fileLines =
    {
        $"Line 1:{DateTime.Now:HHmmss}",
        $"Line 2:{DateTime.Now:HHmmss}",
        $"Line 3:{DateTime.Now:HHmmss}"
    };
    File.AppendAllLines(FULL_FILE_NAME, fileLines);
}

/// <summary>
/// When you're looping through a collection and want to write once per item:
/// </summary>
void LinesFromLoop()
{
    using StreamWriter writer = File.AppendText(FULL_FILE_NAME);
    foreach (Foo foo in GetFoos())
    {
        writer.WriteLine(foo.GetMessage());
    }
}

Leave a Reply

Your email address will not be published.