Read a text file from a passed variable

62 views Asked by At

I have looked at all of the similar questions, and they, unless I missed something, do not answer my question; so here goes:

I want to open a text file on my webpage; but The title is a passed variable. I am getting an error when trying to use the variable. Here is my code:

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

The error is.. Expected literal constant

/_READING TEXTFILE.asp, line 8

Const Filename = VTITLE 'file to read
I have tried different ways for the variable, such as &VTITLE ect.

The code works if I put the title in "" such as "101.txt". Can someone help me with this, please?? I do not know how to make a variable into a constant, I guess.

1

There are 1 answers

0
user692942 On

As the VBScript Documentation says;

You can't use variables, user-defined functions, or intrinsic VBScript functions (such as Chr) in constant declarations. By definition, they can't be constants.

So you either switch to using the already declared VTITLE variable or you replace the Const Filename with;

Dim Filename: Filename = VTITLE

Useful Links