C# StreamWriter

Stream abstract type

StreamWriter writes text files. It enables easy and efficient text output. It is best placed in a using-statement to ensure it is removed from memory when no longer needed. It provides several constructors and many methods.

Constructor

Example

New keyword, constructor invocation

We first declare and initialize a new StreamWriter instance in a using construct. Please note how the System.IO namespace is included at the top of the file. The keyword using means different things in different places.

Using
Program that uses StreamWriter: C#

using System.IO;

class Program
{
    static void Main()
    {
	using (StreamWriter writer =
	    new StreamWriter("important.txt"))
	{
	    writer.Write("Word ");
	    writer.WriteLine("word 2");
	    writer.WriteLine("Line");
	}
    }
}

Output
    (Text is in "important.txt" file.)

Word word 2
Line
Steps

In this example, a new StreamWriter is initialized with the file name "important.txt". Three writes are done using StreamWriter. The Write method does not append a newline. The WriteLine methods append a newline "\r\n" at each call.

Output:The program creates the file "important.txt", which is in the same directory as the application.

And:It will contain two lines of text and two newlines. One newline is at the end of the file.

Append text

To continue, we learn it is possible and easy to append text to a file with StreamWriter.
The file is not erased,
but just reopened
and new text is added to the end. We also see how you can specify a full path.

Program that appends to file: C#

using System.IO;

class Program
{
    static void Main()
    {
	// 1: Write single line to new file
	using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
	{
	    writer.WriteLine("Important data line 1");
	}
	// 2: Append line to the file
	using (StreamWriter writer = new StreamWriter("C:\\log.txt", true))
	{
	    writer.WriteLine("Line 2");
	}
    }
}

Output
    (File "log.txt" contains these lines.)

Important data line 1
Line 2
Note

First, a new StreamWriter is initialized and it opens "C:\\log.txt" for appending. The second argument (true) specifies an append operation. The first string is appended to it. If it is empty, the file begins with that string.

True, False

Next:The second using construct reopens the "C:\\log.txt" file and then appends another string to it.

Note:If for some reason the file was deleted, the line will be added just the same.

Loop

Arrow indicates looping

Often when using StreamWriter, you will need to write out an array or List of string data. The best way to do this is to put the loop inside the StreamWriter statement. This avoids creating more than one file handle in Windows.

Note:We use var, which makes the syntax shorter but equivalent in functionality. The file "loop.txt" is opened only once for writing.

Var
Program that loops with StreamWriter: C#

using System.IO;

class Program
{
    static void Main()
    {
	// Use var type which is shorter
	using (var writer = new StreamWriter("loop.txt"))
	{
	    // Loop through ten numbers
	    for (int i = 0; i < 10; i++)
	    {
		// Write format string to file
		writer.Write("{0:0.0} ", i);
	    }
	}
    }
}

Output
    (These numbers are in the file "loop.txt".)

0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

In this example, the for-loop goes through ten numbers and writes a format string to the file each time. The format string can be easily used with Write. You have to specify a substitution marker {0} in the first parameter.

Forstring.Format

Encodings

Programming tip

StreamWriter accepts a parameter that specifies encoding. This is useful in some globalization contexts. Your encoding requirements will vary depending on your project. Many projects will not need specialized encodings.

Using

Using keyword

The using statements in the examples open and prepare the files. At the end of the statements they close and dispose of the resources. If your program does lots of writes, it will manage system resources correctly if you use using.

Return keyword

Early returns. And if your program returns in the middle of a using statement, the resources will still be disposed. This is because of the finally statement, which is how using is compiled.

Tip:Finally statements always run—they are stubborn about that. They will not run only in an Environment.Exit call or a crash.

Finally

Also, you can manually call Dispose and Close on your StreamWriter. You only should do this if you are not using the "using" keyword. This is a more error-prone style. It is not recommended normally.

Summary

The C# programming language

We employed using and StreamWriter in the C# language. This is an excellent class and useful for many C# developers. The using statement here provides a clear and elegant way of disposing of system resources.

Note:StreamWriter is part of a pair of objects. We often use it along with StreamReader. More details are available.

StreamReader

C#: File