The FileSystemObject and associates

The following objects concerned with manipulating and obtaining information on files, folders and drives are exposed by the scripting runtime:

  • FileSystemObject
  • File
  • Files
  • TextStream
  • Folder
  • Folders
  • Drive
  • Drives

An overview of the FileSystemObject, Drives, Drive, Folders, Folder, Files and File classes

These seven classes really bring object-oriented access to the file system to Visual Basic. Until now, VB has offered only limited intrinsic access to these services in the form of functions such as the Dir function. Advanced access to the file system had to be through API calls, a lot of which are difficult to use from VB, involving VB-hostile types such as the FILETIME user-defined type. For example, a frequent question in the VB newsgroups is "How do I get the path to the system directory ? ". You could use the GetSystemDirectory API, but it is simpler to use the GetSpecialFolder method of the FileSystemObject. Another question might be "How do I get the time a file was last modified ? ". Using the API approach, this would involve calling the GetFileTime API and then somehow convert from the returned FILETIME type to a Date variable. Now, just use the DateLastModified property of the File object.

The seven classes are logically arranged in an object model like this:

Object model

This is a fairly deep hierarchy, but accurately models how drives, folders and files are logically arranged in a real file system. Fortunately, it is rarely necessary to do a lot of navigation around the object hierarchy to get things done, because the topmost FileSystemObject class offers a number of shortcut methods to handle drives, folders and files. For example, you could delete a file by navigating to that file, get a reference to that file and then call its Delete method, or you could simply call the DeleteFile method of the FileSystemObject. Both approaches are exemplified below:

The deep approach

  Dim FileSys As FileSystemObject
  Dim File As File
  Dim Folder As Folder
  Dim Drive As Drive

  Set FileSys = New FileSystemObject
  Set Drive = FileSys.Drives("C")
  Set Folder = Drive.RootFolder
  Set Folder = Folder.SubFolders("Temp")
  Set File = Folder.Files("MyFile.txt")
  File.Delete

The shallow approach

  Dim FileSys As FileSystemObject
  Set FileSys = New FileSystemObject
  
  FileSys.DeleteFile "C:\Temp\MyFile.txt"

The latter approach is not only simpler and more elegant, it is also likely to execute a lot faster. However, there are times when the "deep" approach is preferred, such as when iterating through a large number of folders or files.

Navigating the hierarchy

The FileSystemObject is the externally creatable class. Instances of the six other classes are returned to you via the various methods and properties. From an instance of the FileSystemObject you access a drive via its Drives collection. From a drive you access its folders via its RootFolder property to get a reference to the root folder. Given this reference you can drill your way down the folder tree by recursively accessing the SubFolders collection of a Folder object. Also, from that object you can gain access to a file by retrieving a File object from Folder object's Files collection. To move upwards in the hierarchy, use the ParentFolder or Drive properties of the Folder and File objects to access their parent folder or drive, respectively.

Members of the Drives, Folders and Files classes

These classes are collections of Drive, Folder and File objects, respectively. They are not of the generic VBA.Collection type, but are custom collection classes. All three classes have a Count and an Item property (the default). In addition, the Folders class has an Add method that you can use to create folders. The collection classes support iterating with the For...Each...Next syntax.

To get an idea of the functionality of the non-collection classes it is probably most instructive to see a list of their methods and properties:

Members of the FileSystemObject class
Method (m) / Property (p)HelpString
BuildPath (m)Generate a path from an existing path and a name
CopyFile (m)Copy a file
CopyFolder (m)Copy a folder
CreateFolder (m)Create a folder
CreateTextFile (m)Create a file as a TextStream
DeleteFile (m)Delete a file
DeleteFolder (m)Delete a folder
DriveExists (m)Check if a drive or a share exists
Drives (p) (read-only)Get drives collection
FileExists (m)Check if a file exists
FolderExists (m)Check if a path exists
GetAbsolutePathName (m)Return the canonical representation of the path
GetBaseName (m)Return base name from a path
GetDrive (m)Get drive or UNC share
GetDriveName (m)Return drive from a path
GetExtensionName (m)Return extension from path
GetFile (m)Get file
GetFileName (m)Return the file name from a path
GetFolder (m)Get folder
GetParentFolderName (m)Return path to the parent folder
GetSpecialFolder (m)Get location of various system folders
GetTempName (m)Generate name that can be used to name a temporary file
MoveFile (m)Move a file
MoveFolder (m)Move a folder
OpenTextFile (m)Open a file as a TextStream
Members of the Drive class
Method (m) / Property (p)HelpString
AvailableSpace (p) (read-only)Get available space
DriveLetter (p) (read-only)Drive letter
DriveType (p) (read-only)Drive type
FileSystem (p) (read-only)Filesystem type
FreeSpace (p) (read-only)Get drive free space
IsReady (p) (read-only)Check if disk is available
Path (p) (read-only) (default)Path
RootFolder (p) (read-only)Root folder
SerialNumber (p) (read-only)Serial number
ShareName (p) (read-only)Share name
TotalSize (p) (read-only)Get total drive size
VolumeName (p) (read-write)Name of volume
Members of the Folder class
Method (m) / Property (p)HelpString
Attributes (p) (read-write)Folder attributes
Copy (m)Copy this folder
CreateTextFile (m)Create a file as a TextStream
DateCreated (p) (read-only)Date folder was created
DateLastAccessed (p) (read-only)Date folder was last accessed
DateLastModified (p) (read-only)Date folder was last modified
Delete (m)Delete this folder
Drive (p) (read-only)Get drive that contains folder
Files (p) (read-only)Get files collection
IsRootFolder (p) (read-only)True if folder is root
Move (m)Move this folder
Name (p) (read-write)Get name of folder
ParentFolder (p) (read-only)Get parent folder
Path (p) (read-only) (default)Path to folder
ShortName (p) (read-only)Short name
ShortPath (p) (read-only)Short path
Size (p) (read-only)Sum of files and subfolders
SubFolders (p) (read-only)Get folders collection
Type (p) (read-only)Type description
Members of the File class
Method (m) / Property (p)HelpString
Attributes (p) (read-write)File attributes
Copy (m)Copy this file
DateCreated (p) (read-only)Date file was created
DateLastAccessed (p) (read-only)Date file was last accessed
DateLastModified (p) (read-only)Date file was last modified
Delete (m)Delete this file
Drive (p) (read-only)Get drive that contains file
Move (m)Move this file
Name (p) (read-write)Get name of file
OpenAsTextStream (m)Open a file as a TextStream
ParentFolder (p) (read-only)Get folder that contains file
Path (p) (read-only) (default)Path to file
ShortName (p) (read-only)Short name
ShortPath (p) (read-only)Short path
Size (p) (read-only)File size
Type (p) (read-only)Type description

 

The FileSystemObject sample displays properties of drives, folders and files on the system.


The TextStream Class

The TextStream class makes it easy to work with text files. There isn't anything in the class that you can't do with the intrinsic VB file functions, but it sure makes it a lot easier. All the lower-level details are taken care of by the class internals, leaving it to the developer to handle the higher-level file I/O in an object-oriented way. In order to work with a TextStream you need a working FileSystemObject object, because you need its two methods CreateTextFile and OpenTextFile. The former creates and opens a physical file and hands you over a TextStream object that you can write to. The OpenTextFile method opens an existing file for reading or writing (you can't do both at the same time). If you have a live File object you can also use its OpenAsTextStream method to same effect.

The class maintains an internal file pointer that indicates the current position in the stream during reading or writing. The Line property returns the current line and the Column property returns the current column, i.e. the character offset from the start of the line. There are three methods for reading that allow you to read one character at a time, one line at a time or the whole file in one go. There are also three methods for writing, one for writing a line, one for writing an arbitrary number of characters and one for writing blank lines.

Members of the TextStream class
Method (m) / Property (p)HelpString
AtEndOfLine (p)Is the current position at the end of a line?
AtEndOfStream (p) Is the current position at the end of the stream?
Close (m)Close a text stream
Column (p)Current column number
Line (p)Current line number
Read (m)Read a specific number of characters into a string
ReadAll (m)Read the entire stream into a string
ReadLine (m)Read an entire line into a string
Skip (m)Skip a specific number of characters
SkipLine (m)Skip a line
Write (m)Write a string to the stream
WriteBlankLines (m)Write a number of blank lines to the stream
WriteLine (m)Write a string and an end of line to the stream