C# Language File and Stream I/O Writing lines to a file using the System.IO.StreamWriter class

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The System.IO.StreamWriter class:

Implements a TextWriter for writing characters to a stream in a particular encoding.

Using the WriteLine method, you can write content line-by-line to a file.

Notice the use of the using keyword which makes sure the StreamWriter object is disposed as soon as it goes out of scope and thus the file is closed.

string[] lines = { "My first string", "My second string", "and even a third string" };
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\MyFolder\OutputText.txt"))
{
    foreach (string line in lines)
    {
        sw.WriteLine(line);
    }
}

Note that the StreamWriter can receive a second bool parameter in it's constructor, allowing to Append to a file instead of overwriting the file:

bool appendExistingFile = true;
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\MyFolder\OutputText.txt", appendExistingFile ))
{
    sw.WriteLine("This line will be appended to the existing file");
}


Got any C# Language Question?