Wednesday, October 19, 2011

Reading Text Files in an ASP.NET Web Page


Introduction


There are many real-world situations in which you may wish to read part of or an entire text file into a string variable in a Web page. To read a text file in classic ASP you would simply use the FileSystemObject. In fact, there is an entire FAQ category on the FileSystemObject at ASPFAQs.com.



While you can use the FileSystemObject in an ASP.NET Web page it will impose some serious performance constraints. Rather you should use the classes provided by the .NET Framework to read files. This article examines how to read text files. In a future article I will examine how to use the .NET Framework to read XML files.

File or FileInfo?


There are a number of ways to open a text file in the .NET Framework. All of these methods, though, reside in one of two classes, both of which can be found in the System.IO namespace. These two classes are File and FileInfo. The difference between the two is slight. The File class is composed exclusively of shared (static) methods, while the FileInfo class is not. Shared methods are methods that can be invoked without requiring an instance of the class to invoke. For example, using these classes to, say, delete a file, would go like so:
'Using the File class
File.Delete(fileName)

'Using the FileInfo class
Dim fInfo as FileInfo
fInfo = new FileInfo(fileName)
fInfo.Delete()

Note that the File class's Delete method takes a single parameter, the file to delete, and is invoked without creating an instance of the File class. Alternatively, the FileInfo class's Delete method takes zero parameters, the file to be deleted is the one that was specified in the FileInfo's constructor.
Personally I prefer the File class and will be using it for these examples. Which one you choose is a personal choice. I would wager there is a very, very slight performance advantage in using theFile class since you don't have to undergo the overhead involved in object creation, but that assumption is really just speculation. (If you're interested, I invite you to run some benchmark tests on the two classes, and let me know what you find!)

Opening the File


The simplest way to open a text file for reading is to use the OpenText method. This method opens a text file encoded in UTF-8 (ASCII). You can use the more generic Open method to explicitly specify the file mode (create/open/append/truncate), the file access (read/write/read-write), and the file sharing rights; however, if you're just wanting to read a text file, the OpenText method should be sufficient.The OpenText method returns a StreamReader object that allows you to read the contents of the file you've just opened. Hence, to open a file, our ASP.NET code might look like:

<%@ 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)

...

Note that on the first line we import the System.IO namespace, since that's the namespace the File class resides in. Next, in our Page_Load event handler we create a string named FILENAME that contains the complete physical path to the file we wish to open (such as C:\Inetpub\wwwroot\Rand.txt). Note that the Server.MapPath in ASP.NET is identical to that in classic ASP (to learn more aboutServer.MapPath be sure to read: Using Server.MapPath).

Reading the Contents of the File


Most commonly you'll either want to read the next line of the text file or you'll want to read the entire contents of the text file into a string. In the latter case, simply use the ReadToEnd() method like so:
...

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

...

If you want to read one line at a time, you need to first make sure that there is more contents of the file to be read. You can use the Peek() method to accomplish this. Peek() returns the next character in the stream (without removing it), and returns a -1 when there are no more characters; thus you can simply loop while objStreamReader.Peek() <> -1, and, in each iteration of the loop, use the ReadLine() method to read the next line from the file, like so:

While objStreamReader.Peek() <> -1
someString = objStreamReader.ReadLine()
'... do whatever else you need to do ...
End While


VERY IMPORTANT! Closing the StreamReader


When you're done reading the file it is very important that you close the StreamReader using the Close() method. If you forget to do this the ASP.NET Web pages can continue to access this file just fine, but if you attempt to access the file via another user, or if you attempt to delete the file or overwrite the file you will get access denied errors, because the ASP.NET process is still holding a read lock on the file. So just be certain to close the file when you're done.

Conclusion


A complete example can be seen at the end of this article. It simple opens up a hard-coded text file, reads the file's entire contents into a string, and then dumps the string into a server-side label Web control. You can also try out a live demo of the complete example.As you can see, reading text files through an ASP.NET Web page is not at all difficult. While the syntax differs a bit from that of the FileSystemObject syntax you may be familiar with, it is nevertheless very straightfoward and easy to learn. For more information on reading and writing files in ASP.NET be sure to check out this sample chapter from ASP.NET: Tips, Tutorials, and Code.!
Happy Programming!

  • By Scott Mitchell

    A Complete Example
    <%@ 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 carriage returns with <br>s
    lblNicerOutput.Text = contents.Replace(vbCrLf, "<br>")

    objStreamReader.Close()
    end sub
    </script>

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