Library code snippets

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

Comments

  1. 12 Jun 2009 at 07:44

    I have been using the same to read an excel file(Exel 2002 service pack 3), but this code is not working for 2007 excel can anybody help on this. Thanks, Srinivas.

  2. 11 Jun 2009 at 16:03

    Hi James,

    This article is very nice.

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Reading a file using the FileSystemObject.

Leave a comment

Sign in or Join us (it's free).

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...
AddThis

Related discussion

Related podcasts

  • Scott Guthrie

    Scott catches up with Scott Guthrie in an interview covering Ajax, Asp 2.0, extender controls, CSS adapters and more.

Events coming up

We'd love to hear what you think! Submit ideas or give us feedback