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
OpenText() method. This can be accomplished in the following single line of code:
StreamReader sr = File.OpenText(“C:\\test.txt”);
A couple quick things to note: first, since these classes –
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
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
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" />
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.
Writing to a Text File
File class provides two methods for writing to text files:
AppendText(), both of which take the physical path to a file as its sole argument. As their names suggest,
CreateText() is used for creating new files while
AppendText() is useful for appending content to existing files. That is, if the file that you pass into the
CreateText() function already exists, the file will be overwritten. With
AppendText() if the file exists, the contents will be appended to the end of this existing file’s contents.
Both methods return a
StreamWriter object. The
StreamWriter has two very useful methods for writing content to a file:
Write(stuff to write)
WriteLine(stuff to write)
Both methods have a number of overloaded versions, meaning that you can pass in a string, a character, a number, or whatever, into either of these methods. The difference between the two, as their name makes clear, is that
WriteLine() adds an end-of-line character after the input provided.
The following source code demonstrates how to append some output to an existing file. As with reading the file, be certain to
Close() the stream when you are done writing the file.
<%@ Import Namespace="System.IO" %> <script language="vb" runat="server"> sub Page_Load(sender as Object, e as EventArgs) 'Open a file for writing Dim FILENAME as String = Server.MapPath("Output.txt") 'Get a StreamWriter class that can be used to write to the file Dim objStreamWriter as StreamWriter objStreamWriter = File.AppendText(FILENAME) 'Append the the end of the string, "A user viewed this demo at: " 'followed by the current date and time objStreamWriter.WriteLine("A user viewed this demo at: " & DateTime.Now.ToString()) 'Close the stream objStreamWriter.Close() 'Read the file, displaying its contents '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() 'We may wish to replace carraige returns with <br>s lblNicerOutput.Text = contents.Replace(vbCrLf, "<br>") objStreamReader.Close() end sub </script> <asp:label runat="server" id="lblNicerOutput" Font-Name="Verdana" />
The above code is relatively straightforward: it simply appends a string with the current date/time to the file
Output.txt. After the writing stream is closed, a stream for reading is opened, and the contents of the file are read and displayed in the Label Web control.
In this article we examined how to read and write to text files through an ASP.NET Web page using the appropriate .NET Framework classes. We also discussed what streams are and their utility. When working with files through an ASP.NET Web page, be sure to keep security settings in mind. In order for code from an ASP.NET Web page to be able to muck with files, the ASPNET user account must have the appropriate permissions on the directory/files being tinkered with.
see : http://www.4guysfromrolla.com/articles/072303-1.2.aspx