//
you're reading...
ASP.NET, Database, IT-Center, SQL Server, Web Based

ASP.NET : Read & Write Text 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" />

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

The File class provides two methods for writing to text files: CreateText() and 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.

Conclusion

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.

Happy Programming!
__________________________________________________________________________
see : http://www.4guysfromrolla.com/articles/072303-1.2.aspx

About berbagisolusi

Berbagi merupakan sebuah bentuk simbol keikhlasan untuk membantu dan menolong, sedangkan solusi adalah cara menyelesaikan masalah. Setiap manusia pasti mengalami masalah, tetapi kita tidak perlu mengalami masalah yang sama jika orang lain pernah mengalami dan kita tahu hal tersebut.

Discussion

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 9 other followers

April 2012
M T W T F S S
« Mar   May »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Archives

Web Statistic

Blog Stats

  • 149,580 hits
%d bloggers like this: