Essential C# File and Stream IO  Suggest an edit

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

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


Table Of Contents
22 Enum
25 GUID
96 File and Stream IO
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close