Writing to text file in C#

Here are the basic ways of writing text to a file. Each of these will create a new file, or overwrite if the file already exists. 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()
{
    const string FILE_CONTENTS = "This is my file";
    File.WriteAllText(FULL_FILE_NAME, FILE_CONTENTS);
}

/// <summary>
/// When you have a collection of lines:
/// </summary>
void Lines()
{
    string[] fileLines =
    {
        "Line 1",
        "Line 2",
        "Line 3"
    };
    File.WriteAllLines(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.CreateText(FULL_FILE_NAME);
    foreach (Foo foo in GetFoos())
    {
        writer.WriteLine(foo.Name);
    }
}

Leave a Reply

Your email address will not be published.