StreamWriter Class in C#

StreamWriter class is useful for writing character based data to a text stream. By default it uses Unicode encoding, it can also work with other character sets, System.Text.Encoding object can be passed to the constructor to make it work with specific character set.

StreamWriter derives from an abstract type TextWriter. TextWriter provides basic functions to write to a character stream. StreamWriter implements IDisposable interface and also provides Async methods to write data asynchronously.

StreamWriter can work with an existing file, append or overwrite option is passed as Boolean value to the constructor. By default if files exists, it overwrites the contents in the file. You have to set append parameter to true to force it to append to the existing file. If the file does not exist, it creates a new file.

Some of the methods supported by StreamWriter class are list below. For a complete list of methods, please refer to Microsft.NET documentation.




Writes the text representation of input to the text stream without newline constant. It has many overloads, input is converted to string.


Writes the input string to the text stream with a newline constant.


Clears all the buffer from the writer buffer and writes all the data to the underlying device. Writer stream is not closed.


Flushes and closes the writer and also frees any associated resources.


StreamWriter Code Example

Below code snippet shows how to use StreamWriter class. Try to use Using statement when dealing with StreamWriter objects, so that the object is disposed immediately.

    // Using statement is used to dispose the object immediately.
    using (StreamWriter writer = new StreamWriter("output.txt", true))
        // Writes string without newline constant.
        writer.Write("Writing from StreamWriter");

        // Writes the input with a newline constant.
        writer.WriteLine("Writing a Line");

        // Clears and writes buffer to device.

        // Closes the object and underlying stream