When you think ASP, think...
Recent Articles xml
All Articles
ASP.NET Articles
Related Web Technologies
User Tips!
Coding Tips
spgif spgif

Book Reviews
Sample Chapters
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Stump the SQL Guru!
Web Hosts
Author an Article
spgif spgif

ASP ASP.NET ASP FAQs Feedback topnav-right
Print this Page!
Published: Wednesday, July 23, 2003

Reading and Writing Text Files with the .NET Framework

By 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.

- continued -

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 - DirectoryInfo, Directory, FileInfo, and 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.

Understanding Streams

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).

Examining the File Class

The File class, found in the System.IO namespace, provides a set of static methods for interacting with files on the Web server's file system. (There also exists a class called FileInfo which 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 File and FileInfo, be sure to read: Displaying the Files in a Directory using a DataGrid.) Of particular interest in the File class for this article are a few methods that allow for creating, appending, and reading from a text file. These methods are:

  • CreateText(FileName)
  • AppendText(FileName)
  • OpenText(FileName)

The CreateText() and AppendText() methods return a StreamWriter object. The 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 to the CreateText() or AppendText() method. Similarly, the OpenText() 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 StreamReader to the specified file. This is accomplished by using the File class's OpenText() method. This can be accomplished in the following single line of code:

Dim sr as StreamReader = File.OpenText("C:\test.txt")

// C#
StreamReader sr = File.OpenText("C:\\test.txt");

A couple quick things to note: first, since these classes - StreamReader and File - 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 through Server.MapPath(). (For more information on using Server.MapPath() see Using Server.MapPath().)

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:

  • ReadLine(), and
  • ReadToEnd()

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 StreamReader class 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 the technical documentation.

Whenever you are done reading from a file you should always close the stream using the stream's Close() 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:

<%@ Import Namespace="System.IO" %>
<script language="vb" runat="server">
  sub Page_Load(sender as Object, e as EventArgs)
    'Open a file for reading
    Dim FILENAME as String = Server.MapPath("Rand.txt")

    'Get a StreamReader class that can be used to read the file
    Dim objStreamReader as StreamReader
    objStreamReader = File.OpenText(FILENAME)

    'Now, read the entire file into a string
    Dim contents as String = objStreamReader.ReadToEnd()

    'Set the text of the file to a Web control
    lblRawOutput.Text = contents
    'We may wish to replace carraige returns with <br>s
    lblNicerOutput.Text = contents.Replace(vbCrLf, "<br>")
  end sub

<b>Raw File Output</b><br />
<asp:label runat="server" id="lblRawOutput" />
<b>Nicer Output</b><br />
<asp:label runat="server" id="lblNicerOutput" Font-Name="Verdana" />
[View a Live Demo!]

In this part we saw how to read from a text file using the File class's OpenText() method and a StreamReader. In Part 2 we'll look at how to write to a text file.

  • Read Part 2!

  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article