BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 2.0+

Writing to Text Files with StreamWriter

One of the simplest, yet very flexible, manners for storing information is within a text file. Such a file allows the storage of data in a human-readable and easily edited format. You can create text files using the .NET framework's StreamWriter class.

Text Files

Text files provide one of the simplest types of storage for information but are incredibly flexible. They can store structured information, as in comma-separated values (CSV) files or XML documents, or unstructured information such as plain text created with the Notepad utility. Although they do not provide the functionality of a database, they are still very useful. One common use is to allow interoperability between applications, particularly when interacting with legacy systems.

StreamWriter Class

The StreamWriter class is a standard class within the System.IO namespace. The class allows character data to be sent to a stream, including a text file, for recording or processing. The character data can be sent with various standardised encoding options such as UTF, Unicode, etc.

Creating a Text File

In this article we will write the code required to create and populate a new text file and to append information to a pre-existing document. If you wish to follow the examples, create a new console application. To simplify the references to the StreamWriter class, add the following using directive to the Program class.

using System.IO;

Creating a StreamWriter

The first step to creating a new text file is the instantiation of a StreamWriter object. The most basic constructor for StreamWriter accepts a single parameter containing the path of the file to work with. If the file does not exist, it will be created. If it does exist, the old file will be overwritten.

To create the StreamWriter, add the following line of code to the Main method of the program. If the filename specified already exists on your system, change the string parameter to another path so that you do not risk losing important information.

StreamWriter writer = new StreamWriter(@"c:\temp\test.txt");

NB: The path can be file path, a UNC network share or another location that can accept information from a stream. This includes target locations that do not store the data on disk.

Writing Text to the File

Information can be written to the StreamWriter, and ultimately the file, using two of the class's methods. The WriteLine method stores an entire line of characters, ending with a carriage return in readiness for a new line. The simplest variation requires a string parameter containing the characters to be written.

writer.WriteLine("Line 1");

If you do not wish to end the line, you can use the Write method. This method is almost identical to WriteLine, except that it does not append the carriage return.

writer.Write("Line ");
writer.WriteLine("2");

Both WriteLine and Write can be used to output many other types of data, such as numbers, DateTime values and objects. They can also be used with a template string and a series of parameters in the same manner as the String.Format method. For example:

writer.WriteLine("Line {0}", 3);

Closing the File

Once all of the required information has been written to the file, you should call the StreamWriter's Close method. This ensures that any buffered information is sent to the stream and frees any resources that are in use. Once the StreamWriter is closed, the text file will be complete.

writer.Close();

If you have added all of the above code to the Main method of the console application, run the program now. The file should be created and will contain the following text:

Line 1
Line 2
Line 3

Disposing

The StreamWriter class implements the IDisposable interface to enable the resources that it allocates to be freed on demand, or when the garbage collector destroys the object. When you call the Close method, this actually calls Dispose automatically. When you have finished working with a StreamWriter you can call Dispose instead of Close. This gives the possibility of containing the StreamWriter calls within a using statement, making the code more elegant and ensuring that the object will be disposed correctly. To do so, replace all of the code in the Main method with the following:

using (StreamWriter writer = new StreamWriter(@"c:\temp\test.txt"))
{
    writer.WriteLine("Line 1");
    writer.Write("Line ");
    writer.WriteLine("2");
    writer.WriteLine("Line {0}", 3);
}

Appending to a Text File

Often you will need to append text to an existing file, rather than simply overwriting it. An overloaded version of the StreamWriter constructor allows you to specify whether you wish to overwrite or append by adding a Boolean parameter. If the parameter is set to true, text sent to the StreamWriter will be added at the end of the existing information. If set to false, the file will be replaced. In either case, if the specified file does not exist it will be created.

To reopen the file and append information to it, modify the constructor line as follows. Run the program and review the file's contents to see the results.

using (StreamWriter writer = new StreamWriter(@"c:\temp\test.txt", true))

Text Encoding

The last example in this article allows you to change the encoding method for the text written to the file. By default, the StreamWriter uses UTF-8 encoding. If you need to use an alternative standard, you can specify a third parameter that accepts an object of the Encoding class, from the System.Text namespace. This class includes several static properties that provide other encoding formats.

To demonstrate, modify the constructor as follows to specify that the StreamWriter should use Unicode text:

using (StreamWriter writer = new StreamWriter(@"c:\temp\test.txt", true, Encoding.Unicode))

This completes the article. In the next article I will describe how to read information from text files using the StreamReader class.

16 September 2009