65.9K
CodeProject 正在变化。 阅读更多。
Home

在 ASP 中读取文本文件。

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.96/5 (13投票s)

2000 年 1 月 21 日

CPOL
viewsIcon

774174

downloadIcon

4085

如何在服务器上使用 VBScript 在 ASP 中读取文本文件。

在任何编程语言中最重要的一项任务之一是能够读取和写入文件。在 ASP 中涉及的步骤与许多其他语言没有不同。

  1. 指定文件位置
  2. 确定文件是否存在
  3. 获取文件句柄
  4. 读取内容
  5. 关闭文件并释放所有使用的资源

ASP 中的文件 I/O 可以使用 FileSystemObject 组件完成。打开文本文件时,只需将其作为文本流打开,然后使用该文本流来访问文件内容。

FileSystemObject 允许您执行所有文件和文件夹处理操作。它可以返回一个文件,然后将其作为文本流打开,也可以直接返回一个文本流对象。

在以下内容中,我将介绍两种不同的方法。第一种方法获取一个文件对象,并使用该对象打开文本流,第二种方法直接从 FileSystemObject 打开文本流。

方法 1

<% 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 "<p><b>File: " & Filename & " (size " & FileSize  &_
                   " bytes)</b></p><hr>"
    Response.Write "<pre>"

    ' 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 "</pre><hr>"

    Set TextStream = nothing
    
Else

    Response.Write "<h3><i><font color=red> File " & Filename &_
                       " does not exist</font></i></h3>"

End If

Set FSO = nothing
%>

方法 2

<% 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 "<pre>" & Contents & "</pre><hr>"
    TextStream.Close
    Set TextStream = nothing
    
Else

    Response.Write "<h3><i><font color=red> File " & Filename &_
                   " does not exist</font></i></h3>"

End If

Set FSO = nothing
%>
© . All rights reserved.