从传递的变量中读取文本文件

Read a text file from a passed variable

提问人:Penguin 提问时间:10/26/2023 最后编辑:user692942Penguin 更新时间:10/26/2023 访问量:39

问:

我看过所有类似的问题,除非我遗漏了什么,否则它们不会回答我的问题;所以这里是:

我想在我的网页上打开一个文本文件;但标题是一个传递的变量。我在尝试使用变量时遇到错误。这是我的代码:

Option Explicit

Response.CodePage=65001
Response.CharSet="UTF-8"
DIM VTITLE

VTITLE = REQUEST("TITLE_")&".TXT"


Const Filename = VTITLE 'file to read in this case it is 101.txt
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

错误是.. 预期的文本常量

/_READING TEXTFILE.asp,第 8 行

const Filename = VTITLE '要读取
的文件 我尝试了不同的变量方法,例如 &VTITLE 等。

如果我将标题放在“”中,例如“101.txt”,则代码有效。 有人可以帮我解决这个问题吗??我猜我不知道如何将变量变成常量。

VBScript ASP-经典 FSO

评论

0赞 user692942 10/26/2023
您正在尝试使用常量作为变量,线索在名称中。您应该使用 来声明变量。请参阅了解 VBScript 中的 Const 表达式Dim
0赞 Penguin 10/26/2023
我确实使用 Dim 来声明变量。
0赞 user692942 10/26/2023
不,您曾经声明过,但由于某种未知原因,您随后尝试声明为常量(您无法这样做),因此出现错误。要么用于文件名,要么在确实必须时使用。DimVTITLEVTITLEFilenameVTITLEDim Filename: Filename = VTITLE
0赞 user692942 10/26/2023
正如 VBScript 文档所说,“不能在常量声明中使用变量、用户定义函数或内部 VBScript 函数(如 Chr)。根据定义,它们不能是常量。
1赞 Penguin 10/26/2023
这就是我为使它工作所做的。如何标记正确答案??

答:

0赞 user692942 10/26/2023 #1

正如 VBScript 文档所说;

不能在常量声明中使用变量、用户定义函数或内部 VBScript 函数(如 Chr)。根据定义,它们不能是常量。

因此,您要么切换到使用已声明的变量,要么将 with;VTITLEConst Filename

Dim Filename: Filename = VTITLE

相关链接