Daniel M. Hendricks

Read & Write Text Files

You can use this code to read/write text files from ASP.

Read a Text File

<%
Set objFileSysIn = Server.CreateObject("Scripting.FileSystemObject")
varInputFile = "C:\Inetpub\scripts\hits.txt"
Set objTsIn = objFileSysIn.OpenTextFile(varInputFile)

'This reads the next line (or first line if BOF) in the file
MyVariable = objTsIn.ReadLine

'This displays it
Response.write MyVariable
%>

Write to a Text File

<%
Set objFileSys = Server.CreateObject("Scripting.FileSystemObject")
varOutputFile = "C:\Inetpub\scripts\hits.txt"
Set objTsOut = objFileSys.OpenTextFile(varOutputFile, 2, True)

OutText = "This is what will be written to the file."

objTsOut.WriteLine (OutText)
%>

Read All Lines and Step Through Each

<%
Set fso = CreateObject("Scripting.FileSystemObject")
Set infso = fso.OpenTextFile("myfile.txt")

EntireFile = infso.readAll
CurrentLine = split(EntireFile, vbNewline)

For Each strLine in CurrentLine
   Response.Write strLine & ""
Next
%>

Post a Comment

You must be logged in to post a comment.

Tip: Sign up for a free Gravatar to have a photo next to your comment! Your gravatar will follow you around when you post to blogs that support it, based on the e-mail address you use to post.