Reading a text file in a asp.net page

Source: Internet
Author: User
Tags control label rand readline classic asp
asp.net introduction
In the real world, people often want to be able to save some or all of the content of a text file to a Web page variable. In the classic ASP, as long as the simple use of FileSystemObject can be done. In fact, there is a FAQ section in aspfaqs.com to discuss FileSystemObject.
But in the asp.net? FileSystemObject of course, but experience has shown that doing so can seriously affect server performance. Therefore, it is best to use the classes provided by the. NET framework itself to read files. This article is about how to read a text file; I'll also explain how to use the. NET framework classes to read XML files in the future.

File? FileInfo?

In the. NET framework, there are many ways to open a text file. Interestingly, all such methods are concentrated in the two classes in the System.IO namespace. They are the File class and the FileInfo class. The difference between two classes is very small. The methods of the File class are all shared methods (static methods), with the exception of the FileInfo class. Shared methods are methods that can be invoked without creating a class instance. Suppose you want to delete a file with these two classes, you can do this:

' Use the File class
File.delete (FileName)

' Use the FileInfo class
Dim Finfo as FileInfo
Finfo = new FileInfo (fileName)
Finfo.delete ()

Note that the Delete method of the file class takes only one parameter, the file to be deleted, and can be invoked without instantiating the file class. Looking at the FileInfo class again, its Delete method takes no arguments, because the file name is specified in the constructor of the FileInfo class instance.

Personally, I prefer File, so take it as a demonstration. I bet the File class is a little bit more efficient because using it won't bother you because of class instantiation, but that's just guesswork. (If you're interested, you might want to programmatically compare their performance.) When you have finished, please tell me the result! )

Open File

The easiest way to open a text file is to invoke the OpenText method, which opens the text file in UTF-8 (ASCII) format. You can also select the common Open method to specify file operation mode (create/open/append/truncate), Operation Rights (Read/write/read-write), and file share permissions, but since you only need to read the text file, Then the relatively simple OpenText method is enough to deal with.
The OpenText method returns a StreamReader object that can be read from the file that was opened just by accessing the object. Therefore, the ASP.net code used to open the file is roughly as follows:

<%@ Import namespace= "System.IO"%>
<script language= "VB" runat= "Server" >
Sub Page_Load (sender as Object, E as EventArgs)
' Open file in Read Only ' mode
Dim FILENAME as String = Server.MapPath ("Rand.txt")

' Create an instance of the StreamReader class to read the contents of the file
Dim objStreamReader as StreamReader
objStreamReader = File.OpenText (FILENAME)
...

Note that the first line of code imports the System.IO namespace. This is because the File class belongs to this namespace. Also, in the Page_Load event handler, a string FILENAME is created, whose contents are the physical path (such as C:\Inetpub\wwwroot\Rand.txt) of the file to be opened. Finally, the Server.MapPath in ASP.net is also the same as the classic ASP (to better understand the Server.MapPath, please do not forget to read in the http://aspnet.4guysfromrolla.com/webtech/ 121799-1.shtml's "Using Server.MapPath").

Reading text from a file

Now you have two choices: (1) reading the next line of text from the current position of the file to the string, and (2) reading the entire file's text to the string. If this is the latter, you can simply call the ReadToEnd () method:
...
' Now, read the text of the entire file to the string
Dim contents as String = Objstreamreader.readtoend ()
...

But what if it is the former? Before reading the next line of text, you must first confirm that there is still text to read. To do this, you can try the Peek () method. The Peek () method returns the next text character of the specified stream without deleting the character from the stream, or returns 1 if there is no longer a text character to read in the stream. Next, just loop through the return value of Peek (): Loop while Objstreamreader.peek () <> 1, and using the ReadLine () method inside the loop reads the next line of text:

While Objstreamreader.peek () <>-1
somestring = objStreamReader.ReadLine ()
' ... do whatever else your need to do ...
End While

Remember! Close the StreamReader Object!

When you have finished reading all the text and you no longer operate the file, be sure to close the StreamReader object by using the close () method to turn off the file. If you forget to do this, the ASP.net action process will maintain a read-only lock on this file, so you will experience an error message "Access Denied" (Deny access) when you swap with another account, and you will encounter the same error message when you try to delete or overwrite this file. , except that asp.net itself is not affected by the operation of this file. Therefore, be sure to close the file after you complete the operation.

Attached: Complete model procedure

<%@ Import namespace= "System.IO"%>
<script language= "VB" runat= "Server" >
Sub Page_Load (sender as Object, E as EventArgs)
' Open a file as read-only
Dim FILENAME as String = Server.MapPath ("Rand.txt")

' Instantiate a StreamReader object for reading a file
Dim objStreamReader as StreamReader
objStreamReader = File.OpenText (FILENAME)

' Now, read the text of the entire file and save it in a string.
Dim contents as String = Objstreamreader.readtoend ()

' Display text in a Web control
Lblrawoutput.text = Contents

' In order to facilitate browsing, it is best to replace the return character into <br>
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"/>

Conclusion

This article comes with the source code for a demonstration program. The program simply opens a hard-coded (hard-coded) text file and then saves all of its text in a specified string, and then displays the value of the string in a Web control label on the server side.
You see, it's not difficult to read the text file content through the ASP.net page. Although there are some differences in syntax and classic ASP FileSystemObject objects, it's really easy to learn. To better master how to read and write files in asp.net, be sure to read the book "ASP.NET:Tips, tutorials, and code" (see the sample http://www.4guysfromrolla.com/webtech/ CHAPTERS/ASPNET2)!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.