Read text files on ASP. NET pages

Source: Internet
Author: User
Introduction
In the real world, people often want to save part or all of a text file to a Web page variable. In the classic ASP, you can simply use FileSystemObject. In fact, in aspfaqs.com, there is a faq topic dedicated to discussing FileSystemObject.
But in ASP. NET? FileSystemObject can also be used. However, experience shows that this will seriously affect server performance. Therefore, it is best to use the class provided by the. NET Framework itself to read files. This article describes how to read text files, and how to use the. NET Framework class to read XML files.

File? Fileinfo?

In the. NET Framework, there are many ways to open text files. Interestingly, all such methods are concentrated in the two classes of the system. Io namespace. They are file class and fileinfo class. The difference between the two classes is very small. All methods of the file class are shared methods (static methods), with the exception of the fileinfo class. The shared method is a method that can be called without creating a class instance. If you want to delete files using these two classes, you can do this:

'Use the file class
File. Delete (filename)

'Use fileinfo class
Dim finfo as fileinfo
Finfo = new fileinfo (filename)
Finfo. Delete ()

Note that the delete method of the file class only includes one parameter, that is, the file to be deleted, and can be called without instantiating the file class. Let's take a look at the fileinfo class. Its Delete method does not contain parameters because the file name is specified in the constructor of the fileinfo class instance.

Personally, I prefer file, so let's use it for demonstration. I bet that the efficiency of the file class is a little higher, because using it won't worry about class instantiation; but it's just a guess. (If you are interested, program and compare their performance. After you finish, please tell me the result !)

Open a file

The easiest way to open a text file is to call the opentext method, which will open the text file in UTF-8 (ASCII) format. You can also select a common open method to specify the file operation mode (Create/Open/append/truncate) and Operation permissions (read/write/read-write) share permissions with files. However, since you only need to read text files, the relatively simple opentext method is sufficient.
The opentext method returns a streamreader object. You only need to access this object to read the text content from the file you just opened. Therefore, the ASP. NET code used to open a file is roughly as follows:

<% @ Import namespace = "system. Io" %>
<Script language = "VB" runat = "server">
Sub page_load (sender as object, e as eventargs)
'Open the file in read-only mode
Dim filename as string = server. mappath ("rand.txt ")

'Create a streamreader class instance and prepare to read the file content
Dim objstreamreader as streamreader
Objstreamreader = file. opentext (filename)
...

Note that the first line of the 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 content is the physical path of the file to be opened (for example, c: \ Inetpub \ wwwroot \ rand.txt ). Finally, server. mappath in ASP. NET is the same as that in classic ASP (to better understand server. mappath, don't forget to read using server. mappath in http://aspnet.4guysfromrolla.com/webtech/121799-1.shtml).

Read text from a file

Now, you have two options: (1) reading the next line of text from the current position of the file to the string; (2) reading the text from the entire file to the string. For the latter, you only need to 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 a line of text, make sure that the text is readable. For this reason, you can try the peek () method. The PEEK () method returns the next text character of the specified stream, but does not delete the character from the stream. If no text character is readable in the stream,-1 is returned. Next, you just need to traverse the returned value of PEEK () cyclically: loop while objstreamreader. Peek () <>-1, and read the next line of text using the Readline () method inside the loop:

While objstreamreader. Peek () <>-1
Somestring = objstreamreader. Readline ()
'... Do whatever else you need to do...
End while

Remember! Close the streamreader object!

When you read all the text and no longer operate on this file, remember to close the streamreader object using the close () method to close this file. If you forget to do this, Asp. the net operation process will keep the read-only lock status of this file. Therefore, when you use another account to operate this file, you will encounter an error message "Access Denied" (Access denied ); in addition, when you try to delete or overwrite this file, you will also encounter the same error message; only ASP. net itself, but the operations on this file are not affected. Therefore, you must close the file after completing the operation.

Appendix: complete demonstration procedure

<% @ Import namespace = "system. Io" %>
<Script language = "VB" runat = "server">
Sub page_load (sender as object, e as eventargs)
'Open a file in read-only mode
Dim filename as string = server. mappath ("rand.txt ")

'Instantiate A streamreader object for reading files
Dim objstreamreader as streamreader
Objstreamreader = file. opentext (filename)

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

'Display text in a Web Control
Lblrawoutput. Text = Contents

'To facilitate browsing, it is best to replace the carriage return character with <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"/>

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.