Accessing Files with FileSystemObject
The File System Object (FSO) model provides an object-based tool for working with folders and files. It allows you to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files. You can also employ the traditional Visual Basic statements and commands.
The FSO model gives your application the ability to create, alter, move, and delete folders, or to determine if and where particular folders exist. It also enables you to get information about folders, such as their names and the date they were created or last modified.
The FSO model makes processing files much easier as well. When processing files, your primary goal is to store data in an efficient, easy-to-access format. You need to be able to create files, insert and change the data, and output (read) the data. Although you can store data in a database, doing so adds a significant amount of overhead to your application. You may not want to have such overhead, or your data access requirements may not call for the extra functionality associated with a full-featured database. In this case, storing your data in a text file or binary file is the most efficient solution.
The FSO model, contained in the Scripting type library (Scrrun.dll), supports the creation and manipulation of text files through the TextStream object; however, the FSO model does not support binary files. To manipulate binary files, use the FileOpen Function with the Binary keyword.
The following objects make up the FSO model:
|FileSystemObject||Allows you to create, delete, gain information about, and generally manipulate drives, folders, and files. Many of the methods associated with this object duplicate those in the other objects.|
|Drive||Allows you to gather information about a drive attached to the system, such as how much room is available and what its share name is. Note that a "drive" under the FSO model isn't necessarily a hard disk: it can be a CD-ROM drive, a RAM disk, and so forth. A drive also isn't required to be physically attached to the system; it can also be logically connected through a local area network (LAN).|
|Folder||Allows you to create, delete, or move folders, as well as query the system about their names, paths, and other information.|
|File||Allows you to create, delete, or move files, as well as query the system about their names, paths, and other information.|
|TextStream||Enables you to read and write text files.|
For information about the various properties, methods, and events in the FSO model, use the Object Browser in Visual Basic by pressing CTRL+ALT+J and looking at the Scripting type library. If the Scripting type library does not appear in the list, create a reference to it as shown in the next section.
Programming in the FSO Model
Programming in the FSO model entails three main tasks:
- Creating a FileSystemObject object by using the CreateObject method, or by dimensioning a variable as a FileSystemObject object.
- Using the appropriate method on the newly created object.
- Accessing the object's properties.
The FSO model is contained in the Scripting type library, which is located in the file Scrrun.dll. If you don't already have a reference to it, you can create one.
To create a reference to the Scripting type library (Scrrun.dll)
- On the Project menu, click Add Reference, and then click the COM tab.
- Choose Microsoft Scripting Runtime from the Component Name list, and then click Select.
You can now use the Object Browser to view the FSO model's objects, collections, properties, methods, events, and constants.
To create a FileSystemObject object
- Dimension a variable as type FileSystemObject, as in the following code:
Dim fso As New FileSystemObject
- or -
- Use the CreateObject method to create a FileSystemObject object, as in the following code:
fso = CreateObject("Scripting.FileSystemObject")
In the second example,
Scripting is the name of the type library, and FileSystemObject is the name of the object of which you want to create an instance.
Note The first method works only in Visual Basic, while the second method works either in Visual Basic or VBScript.
Security Note Do not make decisions about the contents of a file based on the file name extension. For example, a file named Form1.vb may not be a Visual Basic .NET source file.
The following table shows FSO methods and the tasks that they perform:
|Create a new object||CreateFolder or CreateTextFile|
|Delete a file or folder||DeleteFile or File.Delete; DeleteFolder or Folder.Delete|
|Copy an object||CopyFile or File.Copy; CopyFolder or Folder.Copy|
|Move an object||MoveFile or File.Move; MoveFolder or Folder.Move|
|Access an existing drive, folder, or file||GetDrive, GetFolder, or GetFile|
Note The FSO model does not support the creation or deletion of drives.
As you can see, some functionality in the FileSystemObject object model is redundant. For example, you can copy a file using either the CopyFile method of the FileSystemObject object, or you can use the Copy method of the File object. The methods work the same way; both versions are included to give you maximum programming flexibility.
Note, however, that you don't need to use the Get methods for a newly created object, since the Create functions already return a handle to it. For example, if you create a new folder using the CreateFolder method, you don't need to use the GetFolder method to access its properties, such as Name, Path, or Size. Just set a variable to the CreateFolder function to gain a handle to the newly created folder, and then access its properties, methods, and events.
The Drive object allows you to get information about the various drives attached to a system, either physically or over a network. Its properties contain the following information:
|TotalSize||Total size of the drive, in bytes|
|AvailableSpace, FreeSpace||How much space is available on the drive, in bytes|
|DriveLetter||Letter assigned to the drive|
|DriveType||Type of drive (removable, fixed, network, CD-ROM, or RAM disk)|
|SerialNumber||Drive's serial number|
|FileSystem||Type of file system the drive uses (FAT, FAT32, or NTFS)|
|IsReady||Whether a drive is available for use|
|ShareName, VolumeName||Name of the share and/or volume|
|Path, RootFolder||Path or root folder of the drive|
App.Path, ChDir, ChDrive, and CurDir
If you use the Path property (App.Path), the ChDrive and ChDir statements, or the CurDir function, be aware that they may return a Universal Naming Convention (UNC) path (that is, one beginning with \\Server\Share...) rather than a drive path (such as e:\Folder), depending on how you run your program or project.
App.Path returns a UNC path when:
- You run a project after loading it from a network share, even if the network share is mapped to a drive letter.
- You run a compiled executable file from a network share (but only if it is run using a UNC path).
ChDrive cannot handle UNC paths, and it raises an error when App.Path returns one. You can handle this error by adding
On Error Resume Next before the ChDrive statement, or by testing the first two characters of App.Path to see if they are backslashes.
The command prompt always has a drive path for the current directory, so CurDir is set to a drive path. ChDir does not raise an error, but it fails to change the directory from a drive path to a UNC path. The only workaround for this situation is to locate a local drive that is mapped to the share specified in the UNC path, or to use network commands to create such a mapping.
If the project is loaded into the Visual Basic development environment from a network share — either a UNC path or a mapped drive path — App.Path returns a UNC path when the project is run and ChDrive fails and raises an error. ChDir does not raise an error, but it fails to change the directory. The only workaround for this situation is to manually set the drive and directory.
If more than one person can open the project on the network share, you can use an MS-DOS environment variable to give each person a customized mapping for the share.
The following table shows the methods for carrying out common folder tasks:
|FileSystemObject.CreateFolder||Create a folder.|
|Folder.Delete or |
|Delete a folder.|
|Folder.Move or |
|Move a folder.|
|Folder.Copy or |
|Copy a folder.|
|Folder.Name||Retrieve the name of a folder.|
|FileSystemObject.FolderExists||Find out if a folder exists on a drive.|
|FileSystemObject.GetFolder||Get an instance of an existing Folder object.|
|FileSystemObject.GetParentFolderName||Find out the name of a folder's parent folder.|
|FileSystemObject.GetSpecialFolder||Find out the path of a system folder.|
Sequential Text Files and FSO
Sequential text files (sometimes referred to as a text stream) are useful when you want to read the contents of a file within a FileSystemObject object. You can access sequential text files with these methods:
|CreateTextFile, OpenTextFile, or OpenAsTextStream||Create a sequential text file.|
|Write or WriteLine||Add data to a text file.|
|Read, ReadLine, or ReadAll||Read data from a text file.|
|File.Move or MoveFile||Move a file.|
|File.Copy or CopyFile||Copy a file.|
|File.Delete or DeleteFile||Delete a file.|