0Writing lines to a file using the System.IO.StreamWriter class

suggest change

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");
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents