Reading a Text File
ASP snippets to read the contents of a text file named 'test.txt'.
The first ASP code snippet uses the Server object to read the contents of a text file named test.txt
using the FileSystemObject
. It then writes the file's content to the response stream.
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Set f=fs.OpenTextFile(Server.MapPath("test.txt"), 1)
Response.Write(f.ReadAll)
f.Close
Set f=Nothing
Set fs=Nothing
%>
This version includes error handling, file existence checking, and proper cleanup:
<%
On Error Resume Next
Set fs = Server.CreateObject("Scripting.FileSystemObject")
If Not fs.FileExists(Server.MapPath("test.txt")) Then
Response.Write("File not found.")
Else
Set f = fs.OpenTextFile(Server.MapPath("test.txt"), 1)
If Err.Number = 0 Then
Response.Write(f.ReadAll)
f.Close
Else
Response.Write("Error reading file: " & Err.Description)
End If
End If
Set f = Nothing
Set fs = Nothing
On Error GoTo 0 ' Turn off error handling
%>