When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, July 23, 2003

Reading and Writing Text Files with the .NET Framework
By Scott Mitchell


Introduction
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:

'VB.NET
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>")
    
    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!]

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!


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



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES