Page

10.4.1- The FileSystemObject Object and its Object Model

Created by Brendan Doss.
Last Updated by Jim Minatel.  

PublicCategorized as 10. The Scripting Objects.

Not yet tagged
<< 10.4.0- The FileSystemObject ObjectChapter1010.4.2- Server-Side Includes >>

The FileSystemObject Object and its Object Model

In chapter 6 , we talked about what an object model was. This is a group of related objects that are working together to provide access to a certain group of functions on the server. The FileSystemObject object has an object model associated with it as well. This object model follows this hierarchy:

 

  • FileSystemObject object
    • Drives collection
    • Drive object
      • Folders collection
      • Folder object
        • Files collection
        • File object

 

Let's take a look at each of the objects in the object model and briefly describe what they are used for. Then, our examples will show different ways to use the FileSystemObject object in real-life web applications.

The Drive Object

Each of the Drive objects that form part of the Drives collection contains a wealth of information about a drive in the web server. This information includes:

 

  • Free space available
  • The Volume name of the drive
  • An indication of whether or not the drive is ready
  • The type of file system that exists on the drive
  • The physical type of drive it is
  • A reference to the root folder on the drive

 

Most of the information contained in the Drive object is read-only. You can't change the amount of free space that a drive has available using the Drive object. However, you can change the Volume name of a drive, if it can physically be changed.

The Drives Collection

This collection contains one Drive object for each of the drives on the system. This includes all of the local drives, both fixed and removable, as well as any currently connected network drives.

The Folder Object

A Folder object allows you to access all of the properties of a folder. These properties include the name of the folder, the collection of files within it, the size of the folder in bytes, and what its attributes are (such as whether it's read-only, hidden, compressed, a system file or a folder). In addition, if there are subfolders within this folder, then it will contain a reference to a collection of folder objects that represent its subfolders. With the folder object, you can also copy, delete, and move folders within the file system.

The Folders Collection

The Folders collection contains a set of Folder objects. This collection is a bit different than the others in that you will usually find a Folders collection as a property of a Folder object. If you think about how these objects map to the physical world, then it begins to make sense. With IIS we have wwwroot as our root folder, and then underneath we have BegASPFiles as a subfolder. The Folders collection also provides a way for you to add a folder object to it. This is like adding a sub-folder to an existing folder.

The File Object

The lowest-level object in the FileSystemObject object model is a File object. Each File object allows access to all of the properties of an individual file in the file system. These properties include the file name, the path to the file, a reference to the folder object where the file exists, and the size of the file. With a File object, you can also copy, delete, and move files in the file system. Another method allows you to open the file itself, and read it as a text stream. In the next part of this chapter, we will be looking at the TextStream object and how it can be used to manipulate the actual contents of a file.

The Files Collection

The Files collection contains all of the File objects within a folder. Each Files collection corresponds to a particular folder or sub-folder in the file system. By iterating through a Files collection, you can examine in turn each of the files within a particular folder.

 

Now, let's take a look at a few examples that show you the different ways that you can use the FileSystemObject object.

Try It Out – Display a Directory

When displaying content from a web page, we can either display static information that is retrieved from a file stored on the web server, or we can dynamically create information to be displayed. One thing that we may want to do is combine these two choices. We may want to be able to display a list of the files stored on the web server.

 

With IIS 5.0 we have the ability to enable directory browsing. This can be done from the Properties option of the Action menu of the MMC for the directory we wish to enable browsing for. In the following screenshot we would be enabling browsing for the BegASPFiles directory/application only:

 

Chapter10_image005

 

By checking the Directory Browsing checkbox, then the client is able to view the contents of the selected directory. However, this method has some drawbacks. If there is a default document, such as index.htm in this example, then there is no way to display the directory. Also, if the directory is displayed, then there is no way to control the fact that each file in the directory is also an active link. This has many implications, especially in the area of security. This setting will allow unauthorized individuals to see hidden files and URLs. This is why most commercial sites disable directory browsing.

 

This first example will show how to use the FileSystemObject object to display a listing of the files in the current directory.

 

1.    Using your editor of choice, create the DisplayDirectory.asp file with the following source code.

<HTML>

<HEAD>

<TITLE>Chapter 10 Example - Display Directory</TITLE>

</HEAD>

<BODY>

 

<%

  Dim strPathInfo, strPhysicalPath

  strPathInfo = Request.ServerVariables("PATH_INFO")


  strPhysicalPath = Server.MapPath(strPathInfo)

 

  Dim objFSO, objFile, objFileItem, objFolder, objFolderContents

  Set objFSO = CreateObject("Scripting.FileSystemObject")

 

  Set objFile = objFSO.GetFile(strPhysicalPath)

  Set objFolder = objFile.ParentFolder

  Set objFolderContents = objFolder.Files

%>

 

<TABLE cellpadding=5>

<TR align=center>

  <TH align=left>File Name</TH>

  <TH>File Size</TH>

  <TH>Last Modified</TH>

</TR>

 

<%

  For Each objFileItem In objFolderContents

    Response.Write "<TR><TD align=left>"

    Response.Write objFileItem.Name

    Response.Write "</TD><TD align=right>"

    Response.Write objFileItem.Size

    Response.Write "</TD><TD align=right>"

    Response.Write objFileItem.DateLastModified

    Response.Write "</TD></TR>"

  Next

%>

 

</TABLE>

</BODY>

</HTML>

 

2.    Save the file in your BegASPFiles folder.

3.    View the page in your web browser.

 

Chapter10_image006

 

When you're trying out this example, you might come across the error Object doesn't support this property or method: 'GetFile'. If so, it's because the Scripting Runtime Library (scrrun.dll) hasn't been installed properly. We recommend that you go back and reinstall the Scripting Runtime Library (available from http://msdn2.microsoft.com/en-us/library/ms950396.aspx).

How It Works

After putting all of the requisite header stuff at the top of the page, the first thing that we need to do is determine the physical path to the current file. Our ASP page will display a list of the files in the directory that the file resides in. The URL that is used to display this file is a virtual path. This means that the path is defined by the web server's configuration. The virtual path does not necessarily correspond to the file's location in the drive's local directory tree. It's also very important to remember that, for the FileScriptingObject objects to work, they need the physical path and not the virtual path.

 

To get the physical path to the current file, we need to start with the virtual path to the file. This information can be found in the HTTP variable PATH_INFO. In our example program, this variable contains the following string:

 

/BegASPFiles/displayDirectory.asp

This should look familiar – it's the part of the URL that follows the name of the server. To retrieve this value, we will use the Request object's ServerVariables collection.

 

Now that we have this value, we need to translate it to the physical path. There is a Server object method that will allow you to do this. The MapPath method will take a virtual path and convert it to a physical path. After we convert our virtual path to a physical path, we have:

 

C:\InetPub\wwwroot\BegASPFiles\DisplayDirectory.asp

 

This is the data that we need to use with the FileScriptingObject objects. In this example, the virtual path looks very similar to the physical path. This is a just a coincidence in the way that this particular web server is configured. In other cases, only the file name could be similar.

 

To start working with the FileSystemObject object, we will need to create an instance of it using:

 

Set objFSO = CreateObject("Scripting.FileSystemObject")

 

We create the object and save its reference in the objFSO variable. Before we dive into how the code itself works, let's look at the strategy we will use to generate the directory.

 

We are starting with the physical path to the file. This file is in the directory that we want the contents for. So, we need to find a way to relate this file to the directory that it's in. Fortunately, one of the FileSystemObject objects provides this type of functionality.

 

To get started, we need to get a File object that corresponds to the file that we have the path for. If you remember, the File object allows you to get information about a particular file. The FileSystemObject object itself provides a method called GetFile that will take a physical path to a file and return a reference to a File object that represents that file.

 

Now that we are armed with a File object representing a file in the directory we are interested in, we can use a property of the File object to get a reference to the folder that it's in.

 

We have been using the words directory and folder interchangeably. For those of us who came from the DOS world, our files have always been arranged in directories. With the advent of Windows 95 and the addition of Windows Explorer, the folder term has become more prevalent. But they both still refer to the same thing.

 

One of the properties of the File object is the ParentFolder property. Given a valid file object, this will return a reference to a Folder object that represents the folder that the file resides in. If you have a File object in the root folder, the ParentFolder property will be null (not known or missing). We have now reached our objective of having an object that represents the directory we are interested in.

 

Now it is time to look at the files that are in this directory. To do this, we will use the Files collection that is stored as a property of the Folder object. This collection is a set of File objects; one object for each file in the directory.

To display the files, we will be using a <TABLE> for formatting. There will be three columns in the table, we will display the file name, the size of the file in bytes, and the date and time the file was last modified. The easiest way to go through all of the items in a collection is to use the For Each loop statement.

 

For Each objFileItem in objFolderContents

 

This statement will set up a loop structure that will be called one time for each object in the objFolderContents collection. Each time through the loop, the reference to the current object will be available using the objFileItem variable. The information that we are interested in displaying is available in three properties of the File object:

 

  • objFileItem.Name – returns the name of the file
  • objFileItem.Size – returns the size of the file in bytes
  • objFileItem.DateLastModified – returns the date and time of the last modification of the file

 

Each of these pieces of information will be stored in their own table cell. Before moving to the next item in the collection, we will need to end the current row in the table. Once we have reached the end of the collection, we can end the table, then finish the page and send it back to the client to be displayed.

 

The next example will enhance the directory viewer page that we have just completed. While displaying a list of files is nice, we may want to be able to interact with the files in the list. This will make the directory an interactive directory, similar to the directory provided by the web server, but with you – the developer – in control of the way the information is presented. If we enable the web server to allow directory browsing, then the contents of the directory we are working in would look like this:

 

Chapter10_image007

 

Since this page is generated by the server itself, there is no way that we can change how that page looks. So let's take a look at how to use the FileSystemObject objects to obtain the same information, and using the power of ASP, create a different presentation of the data.

Try It Out – Make the Directory Interactive

1.    Copy the DisplayDirectory.asp file from the last example to a new file and name it InteractiveDirectory.asp.

2.    Using your favorite editor, make the following additions and changes to the InteractiveDirectory.asp file:

<HTML>

<HEAD>

<TITLE>Chapter 10 Example - Display Directory</TITLE>

</HEAD>

<BODY>

 

<%

  Dim strPathInfo, strPhysicalPath


  strPathInfo = Request.ServerVariables("PATH_INFO")

  strPhysicalPath = Server.MapPath(strPathInfo)

 

  Dim objFSO, objFile, objFileItem, objFolder, objFolderContents

  Set objFSO = CreateObject("Scripting.FileSystemObject")

 

  Set objFile = objFSO.GetFile(strPhysicalPath)

  Set objFolder = objFile.ParentFolder

  Set objFolderContents = objFolder.Files

%>

 

<TABLE cellpadding=5>

<TR align=center>

  <TH align=left>File Name</TH>

  <TH>Type</TH>

  <TH>File Size</TH>

  <TH>Last Modified</TH>

</TR>

 

<%

  For Each objFileItem in objFolderContents

%>

 

  <TR>

    <TD align=left>

    <A href="<%= objFileItem.Name %>">

    <FONT FACE="Verdana" SIZE="3">

    <%= objFileItem.Name %></FONT>

    </A>

    </TD>

    <TD align=right>

    <FONT FACE="Tahoma" SIZE="2" COLOR="DarkGreen">

    <%= objFileItem.type %></FONT>

    </TD>

    <TD align=right>

    <FONT FACE="Tahoma" SIZE="2" COLOR="DarkGreen">

    <%= objFileItem.size %></FONT>

    </TD>

    <TD align=right>

    <FONT FACE="Tahoma" SIZE="2" COLOR="DarkGreen">

    <%= objFileItem.DateLastModified %></FONT>

    </TD>

</TR>

 

<%

  Next

%>

 

</TABLE>

</BODY>

</HTML>

 

3.    Save the file in your BegASPFiles folder.

4.    View the page in your web browser.

 

Chapter10_image008

How It Works

We have made three major changes to the previous example to arrive at this new interactive directory display.

 

First, we have added some text formatting of the file information. There are two text styles that we will be using. One will be for the display of the file name itself in the directory listing. The other will be for the display of the other pieces of information about each file. To make the file names stand out, we have put the file names in a different font at a larger font size.

 

Note that while we set the color for the file data information, we did not set a color for the file name. This is because the file name will be an active link to the file. This means that the color of this text will be controlled by the settings in the user's browser. If we were to change the colors, then we run the risk of confusing the user as to which files they may have already visited.

Second, we added an <A HREF> tag to the name of the file itself. This is to replicate the functionality that is in the standard directory browsing display. All files in that display have a link associated with them. This will allow the user to click on the name of the file to navigate to it. To support this functionality in our page, we need to wrap the name of the file with a <A HREF> tag. The value of the HREF will need to be the same as the name of the file, so that when the user clicks on the link they will be taken to that file.

 

Even though the user may be able to navigate to any file in the directory, there may be files present that, when clicked on, will not return any valid information. Other files may actually include information that you don't want the user to be able to see. So while the ability to list files in a directory may be powerful, you need to exercise some care when using it.

 

Finally, we have added another column to our directory display. This column will display the file type for each file. This is the same file type that would be displayed for the file when viewed using Windows Explorer. To display this information, we retrieve it from the Type property of the File object.

 

Displaying directories is a nice feature, but let's look at some of the other things we can do with the FileSystemObject objects. One thing that you see on a lot of web pages is some small text at the bottom of the page that identifies certain properties about the page. Some of these properties include:

 

  • File Name
  • Size
  • Creation Date
  • Last Modification Date
  • Last Accessed Date

 

For a person viewing the page, this information can be helpful in determining the accuracy of the information on the page, or it can be useful for debugging purposes. Whatever it is used for, there should be an easy way to add it to each page. We'll now look at another method that can be used in ASP to further enhance our directory display example; the practice of including information already processed by the server.

<< 10.4.0- The FileSystemObject ObjectChapter1010.4.2- Server-Side Includes >>

Copyright © 2003 by Wiley Publishing, Inc.

Powered by Near-TimeTerms of Services | Privacy Policy | Security Policy |