Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 55,346 times

Related Categories

Reading a file using the FileSystemObject

The FileSystemObject makes it easy for ASP programmers to perform file and folder operations such as reading a file. First, we need to create an instance of the FileSystemObject:

Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

Next, you can check to see if the file exists, using the FileExists method:

If objFSO.FileExists("C:\inetpub\wwwroot\mysite\thefile.txt") Then
    'file exists
End If

Note that we have provided a full path for the FileExists item. If you want to reference a file relative to your script, then you need to use the Server.MapPath method. For example, to check if the file above exists from a script in C:\inetpub\wwwroot\mysite\, you can use

If objFSO.FileExists(Server.MapPath("thefile.txt")) Then
    'file exists
End If

Next, we can go about accessing the file. We do this by calling the OpenTextFile method, which returns a TextStream object:

Dim objTextStream
Set objTextStream = objFSO.OpenTextFile(Server.MapPath("thefile.txt"),1)

Note that the 1 is the value of the fsoForReading constant. The objTextStream has a number of methods of interest to us. Read(characters) reads the specified number of characters from the file. ReadLine returns the contents of a line as a string. If either of these 2 methods again, it will read them from the place you left off. There is also a ReadAll function, which returns the entire contents of the file at once:

Response.Write "Contents of the file:<br>" & objTextStream.ReadAll

So, putting all the code together, we get

Dim objFSO, objTextStream
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

If objFSO.FileExists(Server.MapPath("thefile.txt")) Then
    'file exists
    Set objTextStream = objFSO.OpenTextFile(Server.MapPath("thefile.txt"),1)
    'output the contents of the file
    Response.Write "Contents of the file:<br>" & objTextStream.ReadAll
    'tidy up
    objTextStream.Close
    Set objTextStream = Nothing
End If


'clean up FSO object
Set objFSO = Nothing

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments