readfile_in_asp
1.0.0
如何在 ASP 中使用 VBScript 读取服务器上的文本文件
任何编程语言中最重要的任务之一就是读取和写入文件的能力。 ASP 涉及的步骤与许多其他语言没有什么不同:
ASP 中的文件 I/O 可以使用FileSystemObject
组件来完成。打开文本文件时,您只需将其作为文本流打开,并且您可以使用此文本流来访问文件的内容。
FileSystemObject 允许您执行所有文件和文件夹处理操作。它可以返回一个可以作为文本流打开的文件,也可以直接返回一个文本流对象。
下面我介绍两种不同的方法。第一个方法获取文件对象并使用它打开文本流,第二个方法直接从FileSystemObject
打开文本流。
"
' Open the file
Dim TextStream
Set TextStream = file.OpenAsTextStream(ForReading, TristateUseDefault)
' Read the file line by line
Do While Not TextStream.AtEndOfStream
Dim Line
Line = TextStream.readline
' Do something with "Line"
Line = Line & vbCRLF
Response.write Line
Loop
Response.Write "
<% Option Explicit
Const Filename = " /readme.txt " ' file to read
Const ForReading = 1 , ForWriting = 2 , ForAppending = 3
Const TristateUseDefault = - 2 , TristateTrue = - 1 , TristateFalse = 0
' Create a filesystem object
Dim FSO
set FSO = server . createObject ( " Scripting.FileSystemObject " )
' Map the logical path to the physical system path
Dim Filepath
Filepath = Server . MapPath (Filename)
if FSO.FileExists(Filepath) Then
' Get a handle to the file
Dim file
set file = FSO.GetFile(Filepath)
' Get some info about the file
Dim FileSize
FileSize = file.Size
Response . Write " File: "
& Filename & " (size " & FileSize & _
" bytes)
"
Response . Write " "
' Open the file
Dim TextStream
Set TextStream = file.OpenAsTextStream(ForReading, TristateUseDefault)
' Read the file line by line
Do While Not TextStream.AtEndOfStream
Dim Line
Line = TextStream.readline
' Do something with "Line"
Line = Line & vbCRLF
Response . write Line
Loop
Response . Write "
<% Option Explicit
Const Filename = " /readme.txt " ' file to read
Const ForReading = 1 , ForWriting = 2 , ForAppending = 3
Const TristateUseDefault = - 2 , TristateTrue = - 1 , TristateFalse = 0
' Create a filesystem object
Dim FSO
set FSO = server . createObject ( " Scripting.FileSystemObject " )
' Map the logical path to the physical system path
Dim Filepath
Filepath = Server . MapPath (Filename)
if FSO.FileExists(Filepath) Then
Set TextStream = FSO.OpenTextFile(Filepath, ForReading, False , TristateUseDefault)
' Read file in one hit
Dim Contents
Contents = TextStream.ReadAll
Response . write " "
& Contents & "