Reading and Writing Text Files with the .NET FrameworkBy Scott Mitchell
Ideally, all persistent data should be stored in a database, but oftentimes Web developers find themselves using plain old text files for some kind of persistent storage. There are usually better alternatives, but since this technique is still used quite a bit, it is worthwhile to discuss how to read and write to text files through an ASP.NET Web page.
With classic ASP, all file system actions - such as deleting, copying, moving, or renaming files, reading from files, or writing or appending to files - used the FileSystemObject, a COM component that shipped with Windows and allowed file system access from scripts. The FileSystemObject had many uses in the classic ASP world, and actually has its own FAQ category at ASPFAQs.com, with nearly 20 frequently asked questions.
With ASP.NET you should no longer use the FileSystemObject, but instead the file system classes in
the .NET Framework. Whereas all of the functionality of file system accesses was stuffed into the FileSystemObject
for classic ASP, the .NET Framework separates the functionality into two sets of classes: the first set
of classes -
File - allow
for actions on files and directories. This includes the ability to create a new file, delete an existing
file, find out how many files are in a directory, determine a file's size and last modified date, and
so on. The second set of classes are stream classes, and are used to actually read and write content
to a file.
In this article we will examine how to read and write text files using the appropriate .NET Framework classes.
As aforementioned, to read and write to a file, we use streams. While the name may sound mystifying, the concept of streams is rather simple, really. Think of a stream as a water hose. As you know, a hose has two ends and transports water from one end to the other. By itself, a steam, like a hose, is pretty useless. The utility of a stream/hose makes itself apparent once we attach the stream/hose to something.
For example, imagine we want to fill a pool with water. The pool can be thought of as a repository that holds water. The water source is a spigot, let's say, attached to our house. Now, to fill the pool, we attach a hose from the spigot to the pool, and let the water flow.
Now, to complete the cheesy analogy, replace the words hose with stream, spigot with source of data, water with data, and pool with file. That is, imagine we want to fill a file with some data. The file can be thought of as a repository that holds data. The data source can be anything: user input, the contents of another file, the results of a database query, etc. Now, to fill up the file with data, we attach a stream from our source of data to the file, and let the data flow.
Some streams can support both reading and writing of data; other streams support just reading, or just writing. The key thing to understand, though, is that a stream is merely a connection between sources of data. Streams enable data to flow between these two sources, just like the hose allows water to flow from the spigot (one source of water) to the pool (another source of water).
Fileclass, found in the
System.IOnamespace, provides a set of static methods for interacting with files on the Web server's file system. (There also exists a class called
FileInfowhich provides roughly the same functionality, but not in static method form. For a more detailed discussion on what static methods are, as well as a quick examination of both
FileInfo, be sure to read: Displaying the Files in a Directory using a DataGrid.) Of particular interest in the
Fileclass for this article are a few methods that allow for creating, appending, and reading from a text file. These methods are:
AppendText() methods return a
StreamWriter object, as its name implies, is a stream for writing data.
In this case, the stream will be used to write data to the file specified by the FileName parameter
AppendText() method. Similarly, the
method accepts a string input specifying the path of the file to open for reading. It returns a
StreamReader object, which is used to read the contents from the specified file.
Reading From a Text File
The first step in reading from a text file is hooking up a
StreamReaderto the specified file. This is accomplished by using the
OpenText()method. This can be accomplished in the following single line of code:
A couple quick things to note: first, since these classes -
are located in the
System.IO namespace, you will need to include this namespace in your
code-behind class or ASP.NET Web page. Next, note that in the C# example, all backslashes must be escaped
with two backslashes. Also, realize that in a Web application environment, typically you will
not use hard-coded physical file paths, but file paths relative to the Web application's physical directory
Server.MapPath(). (For more information on using
When opening/writing to a file, you may find that you get a security exception error. If this is the case, it is due to security settings on the Web server. Namely, the ASPNET account is lacking the appropriate permissions for the directory and/or file. To fix this, launch Explorer on the Web server and right-click to the directory you want to be able to read/write files to/from and choose Properties. Then, choose the Security tab; click the Add button and add the ASPNET account with the appropriate permissions.
Once you have a
StreamReader, you will find the two methods the most useful:
Both methods return a string.
ReadLine() returns the characters between the current position
being read from and the end of line character.
ReadToEnd() reads all the characters from
the current position to the end of the file. There are also methods in the
to read a single character, to read a specified block of characters, to examine a single character without
moving the current reading position, and so on. For more information on these methods be sure to view
Whenever you are done reading from a file you should always close the stream using the stream's
method. This lets the file system know that you are done reading from the file. This is not so vital when
just reading from a file, but it definitely more important when writing to a file, since the file
can be locked from other writers until the stream is closed.
The following example demonstrates how to read the entire contents of a file and display them:
In this part we saw how to read from a text file using the
OpenText() method and a
Part 2 we'll look at how to write to a text file.