Asp File in ASP
In Classic ASP, working with files (reading, writing, creating, deleting) is done using the FileSystemObject (FSO).
How to Work with Files in ASP using FileSystemObject
1. Create FileSystemObject
<%Dim fsoSet fso = Server.CreateObject("Scripting.FileSystemObject")%>2. Check if a File Exists
If fso.FileExists(Server.MapPath("test.txt")) Then Response.Write "File exists."Else Response.Write "File does not exist."End If3. Create and Write to a File
Dim filePath, filefilePath = Server.MapPath("test.txt")' Create a new text file and write text to itSet file = fso.CreateTextFile(filePath, True) ' True = overwrite if existsfile.WriteLine "Hello from Classic ASP!"file.CloseSet file = Nothing4. Read from a File
Dim filePath, file, contentfilePath = Server.MapPath("test.txt")If fso.FileExists(filePath) Then Set file = fso.OpenTextFile(filePath, 1) ' 1 = ForReading content = file.ReadAll file.Close Set file = Nothing Response.Write "File content:<br>" & Server.HTMLEncode(content)Else Response.Write "File not found."End If5. Append Text to a File
Dim filePath, filefilePath = Server.MapPath("test.txt")If fso.FileExists(filePath) Then Set file = fso.OpenTextFile(filePath, 8) ' 8 = ForAppending file.WriteLine "Additional line appended." file.Close Set file = NothingElse Response.Write "File not found."End If6. Delete a File
Dim filePathfilePath = Server.MapPath("test.txt")If fso.FileExists(filePath) Then fso.DeleteFile(filePath) Response.Write "File deleted."Else Response.Write "File not found."End IfFile Mode Constants
| Mode Value | Meaning |
|---|---|
| 1 | ForReading |
| 2 | ForWriting |
| 8 | ForAppending |
Clean Up
Set fso = NothingNotes
Use
Server.MapPathto convert a relative URL path to a physical path on the server.Always handle errors when working with files (e.g., file may be locked, no permissions).
Avoid storing sensitive info in plain text files.
If you want examples of reading binary files, uploading files with ASP, or listing files in a folder, let me know!