Book Store  
  Contact Us  
  Links  
  Site Map  
ASP Scripts - file handling

File Handling

 

Open and Read content from a text file

Reading a text file from the web server

<%;
Set fs = CreateObject("Scripting.FileSystemObject")

Set objFile = fs.OpenTextFile("c:\files\myfile.txt")
filecontent = objFile.ReadAll

objFile.close
Set objFile=nothing
Set fs=nothing

response.write(filecontent)
%>

Reading different values from a text file from the web server

<%
Set fs = CreateObject("Scripting.FileSystemObject")

Set objFile = fs.OpenTextFile("c:\files\myfile.txt")
firstname = objFile.ReadLine
lastname = objFile.ReadLine
theage = objFile.ReadLine

objFile.close
Set objFile=nothing
Set fs=nothing

%>
Your first name is <% =firstname %>
Your last name is <%=firstname %>
Your are <%=firstname %> years old

Reading all lines and displaying a line number

<%
Set fs = CreateObject("Scripting.FileSystemObject")

Set objFile = fs.OpenTextFile("c:\files\myfile.txt")

counter=0
do while not objFile.AtEndOfStream
counter=counter+1
singleline=objFile.readline
response.write (counter & singleline & "<br>")
loop

objFile.close
Set objFile=nothing
Set fs=nothing
%>

Create and Write to a text file

<%
thetext="Write this text in the file"

Set fs = CreateObject("Scripting.FileSystemObject")

Set objFile = fs.CreateTextFile("c:\files\myfile.txt", True)
objFile.Write (thetext)

objFile.close
Set objFile=nothing
Set fs=nothing

response.write("File created")
%>

CreateTextFile method as used in the example above has an optional parameter which is either true or false :

A Boolean value that indicates whether an existing file can be overwritten. True indicates that the file can be overwritten and False indicates that the file can not be overwritten. Default is True