ReadFile








<% Option Explicit

' //////////////////////////////////////////////////////////////////

' Demonstration of how to read a file using VBScript in an ASP page.

' - Chris Maunder

' //////////////////////////////////////////////////////////////////



Const Filename = "myfile.txt" ' file to read - CHANGE THIS

' Some constants

Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0


' //////////////////////////////////////////////////////////////////

' First method


' 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


' //////////////////////////////////////////////////////////////////

' Second method


' Create a filesystem object

set FSO = server.createObject("Scripting.FileSystemObject")

' Map the logical path to the physical system path

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
%>










( readfile.html )- by Paolo Puglisi - Modifica del 17/12/2023