The FileSystem Object

In this tutorial, we use the FileSystem object to build a cool script to rotate the images displayed on a page.

The FileSystem object allows us to use ASP to work with files and folders on the hard drive of our web server. We can read, write, create, and delete files and folders using the FileSystem object and the objects that are associated with it.

In this tutorial, we will use the FileSystem object to build a script which displays a random image on a page each time the page is served. Some possible uses might be to illustrate the different areas of countryside on a travel site, or to choose a book to display at random for your affiliate bookstore.

Getting prepared

To get started, identify some images to use and put them all into a single directory on your web server. Store your images in a directory called rotating_images which is in the web root. To keep things simple in the code, make sure you only have images in this directory.

The method

So what do we need to do? First of all, we create an instance of the FileSystem object to find out the names of the files in our directory. We then choose one at random to display in our page. You might like to view the ASP code in a new window, and we'll go through the code together.

The code

We start off with stating that the script is written using VBScript and that we are using Option Explicit, so that we have to dimension our variables before we use them. If we don't dimension the variables first then our script will give us an error when we try to run it. This can help us to notice if we've mis-spelled a variable name somewhere in our code, so it's generally worthwhile. Dimensioning the variables close to the top of the script is a good idea, as it lets you see everything used in the script at a glance.


<%@ Language=VBScript %>
<%

' set checking on so that we have to dimension
' our variables before we can use them
Option Explicit

' dimension our variables first
dim filesys, folder, folder_name_web
dim folder_name_drive
dim files_collection, filecount, filename
dim rand, file, i

Earlier we put our images into the directory rotating_images. Now we tell our ASP script to look there for them. We define the path from our ASP script and then use Server.MapPath() to convert the web server path to the equivalent file system path. Later on in our script, we will need the web server path to the images (so that we can display them), and the file server path, so that we can access them with the FileSystem object. Using Server.MapPath() to do the conversion is generally a good idea, as it makes your code more portable. Using this method you wouldn't need to change your code if you moved hosts.


' store the images directory name in a variable
folder_name_web = "rotating_images/"

' map the folder name as accessible through the web
' to the actual path on the hard-drive.
folder_name_drive = Server.MapPath(folder_name_web)

Now we create an instance of the FileSystem object and use it to query the file system. The FileSystem object is a VBScript object. Just like any object, you have to create an instance of it before using it. Once you have an instance you can examine properties and call methods of the object.


' create a FileSystem Object and use it to get
' a Folder Object
set filesys =
CreateObject("Scripting.FileSystemObject")

If objects, instances, properties and methods are new to you, you might want to read the next section on Object-Oriented Programming (it's not essential - you should be able to follow the remainder of the tutorial without reading the Object-Oriented Programming section). If you're not interested in the details, or you are already familiar with objects, skip on to the following section to carry on with the code.

Object-Oriented Programming for beginners

An object created using object-oriented programming is similar to a real world object. Using the example of a chair, a chair has attributes such as being wooden, and being red. If we were programming this chair object we would call these attributes properties and we might refer to them like this:


my_chair_is_made_of = mychair.material
my_chair_is_coloured = mychair.colour

We can also do things to our chair - we call these methods. So, for example, we might write a check to see if our chair is occupied like this:


is_empty = mychair.IsEmpty()

Methods can also accept parameters. Say we wanted to paint our chair, we might write the code like this:


myChair.Paint("blue")

In our example, we are not dealing with all chairs, but just a single chair. Before we start trying to access the properties and methods, we have to create an instance of our chair. In VBScript we would create an object like this:


set mychair = CreateObject("Chair")

When we've finished with our chair, we should destroy it. The VBScript to do this is:


set mychair = nothing

Object-oriented programming is a very different way of thinking from traditional programming and it usually takes seasoned programmers months to get to grips with. Luckily we are just using some pre-built objects here and don't really need to understand all the details of how they are implemented. Phew!

Back to the code

So we've got as far as creating an instance of our FileSystem object. The next thing to do is associate our FileSystem object with the folder we are interested in and get a list of the files in that folder. To do this, we use a method of the FileSystem object that returns another object - the Folder object. The Folder object allows us to work with folders on the file system. We then use a property of the Folder object called Files to return a collection that contains a set of File objects. Sounds complicated, but it's only two lines of code!


set folder = filesys.GetFolder(folder_name_drive)

' get a collection of all the files in the folder
set files_collection = folder.Files

So far, so good. We've now got a collection of all the files that we might want to display. The next step is to choose one to display at random. To do this, we find out how many files there are using the Count property of the Files collection. We use the Randomize and Rnd functions to generate a random number, rand. We'll use this random number to decide which file to use.


'get the number of files in the collection
filecount = files_collection.Count

' generate a new seed for the Rnd() function
Randomize

' generate a random number between 0
' and filecount - 1
rand = Int(Rnd() * filecount)

We loop through the Files collection until we find the "rand"th file and grab the name to use in our HTML.


' get the name of the file corresponding
' to the random number
i = 0
for each file in files_collection
	filename = file.name
	if i = rand then exit for
	i = i+1
next

The remaining code outputs the HTML page and uses the variables folder_name_web and filename to display our randomly chosen image.


' output the html
%>
<html>

<head>
<title>Rotating Images</title>
</head>

<body>
<table>
  <tr>
    <td><img src="<%=folder_name_web%>
    <%=filename%>"></td>
    <td>Refresh the page to see a randomly
    chosen image.</td>
  </tr>
</table>
</body>

</html>

A Note On Permissions

If you're having trouble running the script we just created, check the permissions on the directory that you put your images into.

Your web server will normally run ASP scripts under a special purpose user account (usually IUSR_MACHINENAME). To make sure that the Web user has access to the directory that you put your images into, right click on the directory to bring up the Properties, choose the Security tab and check that the "IUSR" account has read and execute permission on the directory and read permission on the files inside the directory.

Setting the permissions

An exercise for you

If you managed to get our script running, why not try modifying the code to display a random quote from a text file (where each quote is stored on a new line). You'll need to use the TextStream object for this exercise. You can create a read-only instance of a TextStream object using the following:


Set filetxt = filesys.OpenTextFile
(folder_name_drive & "quotes.txt", 1, False)

We suggest that you count the number of lines in the file and store the value in a variable quote_count (don't forget to dimension your variables near the top of the file). You can then use the SkipLine method to skip to a random line in the file and ReadLine to read the quote contained on that line.


filetxt.SkipLine
quote = filetxt.ReadLine
filetxt.Close

Finally write out the quote somewhere in your HTML.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page