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 & "