Read and write files in ASP

In Aspen it's possible read the content of a fillet e to write in a text file.

The object that is right for us is the FileSystemObject: to open a file we will use OpenTextFile with 3 different modes: read, write, append.

The file can be read either with ReadLine (line by line) or with ReadAll (reads all content).

The mode append differs from the mode writing as it adds text to an already open document appending it to the one already present.



Read and write files in ASP

Read and write files in ASP

With this script we read the contents of the file all at once:

<%
filePath = Server.Mappath(“file_testo.txt”)
Set objFileSystem = Server.CreateObject(“Scripting.FileSystemObject”)
if objFileSystem.FileExists(filePath ) then
'I open file for reading
Set objFile = objFileSystem.OpenTextFile(filePath, 1)
'I write to video file content
Response.Write objFile.ReadAll
'or I put it in a text_content = objFile.ReadAll variable
objFile.Close
Set objFile=Nothing
end if
Set objFileSystem=Nothing
%>

With this script we read the file line by line:
<%
filePath = Server.Mappath(“file_testo.txt”)
Set objFileSystem = Server.CreateObject(“Scripting.FileSystemObject”)
if objFileSystem.FileExists(filePath ) then
Set objFile = objFileSystem.OpenTextFile(filePath, 1)
'I read file line by line until the end of the file
Do While Not objFile.AtEndofStream
Response.Write objFile.ReadLine & “”
loop
objFile.Close
Set objFile=Nothing
end if
Set objFileSystem=Nothing
%>

I write the text in the file (check the folder has write permissions) and if the file does not exist I create it: 

<%
filePath = Server.Mappath(“file_testo.txt”)
Set objFileSystem = Server.CreateObject(“Scripting.FileSystemObject”)
if not objFileSystem.FileExists(filePath) then
'if it doesn't exist I think so
objFileSystem.CreateTextFile(filePath)
end if
Set objFile = objFileSystem.OpenTextFile(filePath, 2)
'I write a line to the file
‘ objFileSystem.OpenTextFile(filePath, 2) -> sovrascrivo file
'objFileSystem.OpenTextFile (filePath, 8) -> add the text to the bottom of the file
objFile.WriteLine ("new file text")
objFile.Close
Set objFile=Nothing
Set objFileSystem=Nothing
%>



add a comment of Read and write files in ASP
Comment sent successfully! We will review it in the next few hours.