Paul is a Visual Basic consultant based in the UK. He is also the author of VB and VBA in a Nutshell: The Languages (O'Reilly & Associates, 1998). He can be contacted at [email protected]
Microsoft's Visual Basic 6 (VB6) is not the revolutionary type of release we saw with VB4 and VB5. Consequently, it would be easy to overlook some of the important features VB6 offers. Much of the enhanced functionality in VB6 has been achieved by the use of external object models; one such improvement is the File-System Object Model (FSOM).
The FSOM first saw the light of day in the second release of VBScript, where it was limited to allowing server-side scripts to access and manipulate text files. For VB6, the FSOM has been extended and made available via the Scripting Run-Time Library -- which can now be directly referenced in a VB project.
The FSOM relates to the drives -- and the folders and files therein -- connected to the local machine. This includes any drive that is part of the local computer -- hard disk, CD-ROM drives, removable media drive, or a drive connected via a network. Network drives do not have to be manually connected to the computer using Explorer or a log-on script. You can access any network drive at run time, given that the interactive user has permission to do so. Listing One for instance, shows how you can obtain a reference to a Drive object on the network.
You can use the Drive object to determine what type of drive you are dealing with. Unfortunately, this information is not as rich as it could be. For example, you cannot determine if a network drive is a compressed network drive or a removable media network drive -- they all simply appear as generic network drives.
Once you have obtained a reference to a Drive object representing the drive you need to work with, you can quickly navigate through folders and subfolders on the drive and obtain information about the files within these folders.
You can use the FSOM to delete, create, and move folders and files. All the methods relating to moving and deleting folders are the same as the functionality in the Windows Explorer, where deleting or moving of a folder affects all the contents of that folder.
Filesystem Objects versus Intrinsic File Functions
Many of the intrinsic file system statements found in VB predate the "visual" of Visual Basic. The information they return is at best minimal because most of the file manipulation functionality is provided by statements (as opposed to Functions), which means that values denoting the success or failure of a particular operation are not returned.
The intrinsic filesystem statements in VB were written when it was unusual for a PC to have more than one drive, let alone access to CD-ROMs, removable media hard drives, and network drives of all types. Therefore, the concept of pointing the whole program at a single drive at any one time was adequate.
For an application running in Windows NT, where it may need to access several different drives on different machines (or even on different continents), the intrinsic VB file system statements are clearly inadequate. By representing any physical drive, folder, or file on the machine, LAN, or WAN by an object, your VB application can hold multiple references to a limitless array of filesystem components -- a far cry from the ChDrive statement.
The property values and information available to you from the FSOM are much richer than that you can obtain from the intrinsic functions. For example, you can return the date and time a file or folder was created and modified, and (if supported by the operating system) the date and time a file or folder was last accessed.
The FSOM gives you much greater functionality; for example, you can use the FSOM to generate valid windows-temporary-file names, or return an object representing special windows folders such as System32 and Temp as in Listing Two.
Perhaps the only downside to the FSOM is the inability to work directly with VB Random Access and Binary files. The File object's Open method returns only a TextStream object. While you can always write code to manipulate the binary data within the file, you'll probably still find this sort of work easier with VB's Open, Get, and Put statements. You can create a File object representing any file type, and obtain property values from it, and move, copy, or delete it; however, you can only open it as a text file.
Accessing the FSOM
The FSOM is part of the Microsoft Scripting Runtime Library (SCRRUN.DLL). To use the objects within this library, you must first add a project-level reference to the library using the References Dialog Box, which (as in VB5) is under the Project menu.
Once you have a project-level reference to the Scripting Runtime Library, you can create an instance of the public "top of the tree" FileSystemObject object; see Listing Three.
Using the FileSystemObject Object
The FileSystemObject is the only object that can be created as new. It sits at the top of the filesystem hierarchy, and also acts as a general-purpose object that allows you to manipulate drives, folders, and files without having to create individual objects for them, thereby relieving you of the chore of having to navigate down through the object model.
Many of the every-day tasks can be completed by simply creating an instance of the FileSystemObject object and calling one of its many methods. For example, to move a folder, you could use Listing Four.
You can also use the FileSystemObject to skip down the object model, bypassing the normal hierarchical structure, and creating instances of the object you require. For example, to create an instance of a particular Folder object, you can simply call the GetFolder method in Listing Five.
Another useful set of properties are available in the FileSystemObject to detect the existence of a drive, folder, or file. Listing Six demonstrates how to test for the presence of a file. For more intensive work with the filesystem objects, you will probably need to resort to the individual objects within the model.
Navigating through the FSOM
If you have any experience of using any object model, then you'll find the FSOM relatively straightforward to use; see Figure 1.
However, there is one wrinkle in the way the object model is traversed. With object models in general, you usually create an instance of a collection object, which then leads to a single object, which can lead to another collection object, and so on. However, when you're dealing with the FSOM hierarchy, you may find it strange that the Folder object can only be instantiated via a Folder object. This is so because the first Folder object created from a Drive object is, in fact, the root folder of the drive. After its creation, you subsequently create a Folder object representing the subfolders in the root.
The Folders collection object is used to obtain a further Folder object representing the subfolders. The Files collection object is accessed via the Folder object, and in turn the File object is accessed via the Files collection. Both the File and Folder objects allow you to navigate back up the hierarchy by providing ParentFolder and Drive properties.
The Drives Collection Object
The Drives collection represents only those drives that are connected to the machine. Unfortunately, there isn't an Add method to allow you to connect a new network drive, however, this functionality is available via the FileSystemObject's GetDrive method. Incidentally, adding a Drive in this manner does not add the drive to the Drives collection.
The Drives collection is keyed on the Drive letter; for example, Drives.Item("C"). Because Item is the default property you can simply use Drives("C").
The Drive Object
The Drive object provides you with information about the size of the drive, its available space, serial number, volume name, and the filesystem being used on the drive. You can also determine if the drive is ready (a useful property when dealing with removable media drives) and return a value representing the type of drive; see Listing Seven.
The Folder Object
The first Folder object you create from the Drive object is the Root Folder in Listing Eight. Once you have created a root folder object (which is an identical type to any other Folder object except its IsRootFolder property is set to True), you can generate a Folder object, which represents the subfolders within the folder.
The Folder object itself contains Move, Delete, and Copy methods, which act both on the referenced folder and on all the files and subfolders contained within. Therefore, when you move a folder, you are moving the folder and the file/folder hierarchy below it. There are properties to determine the cumulative size of all files held within the folder, the date the folder was created, modified, and last accessed.
The Folders Collection Object
The Folder object is a collection of Folder objects. It is created using the SubFolder property of the Folder object. Yes, it does seem strange to create a collection object via a member of the same collection; see Listing Nine.
The Folders collection has the usual Count and Item properties to return further Folder objects, the Item property takes either the ordinal number of the Folder or the folder's name.
The Folders collection also contains an Add method, which lets you create a new Folder within the subfolder. This isn't a virtual addition (that is, just within the Folder collection), it is a physical addition of a new folder on the drive, as in Folders.Add "DataArchive".
The Files Collection Object
As you've probably guessed by now, the Files object is a collection of File objects, representing the files held within a particular folder. You create a Files object using the Files Unlike the Folders collection, the Files collection does not contain an Add method to create new files. In fact the only new files that can be created are textStream files, this is done using either the Folder or FileSystemObject object's CreateTextFile methods, or OpenTextFile method and passing True for the Create parameter. Listings Eleven and Twelve show these two methods.
The File Object
Many of the properties of the File object properties are exactly the same as those for the Folder object. It provides Move, Copy, and Delete methods, and timestamp properties for dates created, modified, and accessed; see Listing Thirteen.
The File object also provides a Type property that returns a string based on the file description held in the registry for the particular file extension (if available). For example an .INI file returns "Configuration Settings," whereas an .FFA file returns "FFA File"
The only type of file that can be opened (and thereby either written to or read) is a text file, which returns the special object TextStream.
The TextStream Object
The TextStream object was the original reason for the FSOM. When VBScript was first released, all file-handling routines had been removed as they where considered unsafe for browser-side scripts. VBScript Version 2 introduced the FileSystemObject which had one sub object -- the Text- Stream, this allowed server-side scripts and ASPs to have some limited ability to create, write to, and read text files.
The TextStream object provides several methods to read a given number of characters, a complete line or the complete file, and similar methods to write back to the file as Listings Fourteen and Fifteen.
The FSOM is an important addition to VB developers' toolboxes. It is easy to use and it provides access to detailed information about drives, folders, and files.
The FSOM is well designed providing a top-level object that can be used for most quick tasks, like copying and moving files and folders. At the same time, it provides a complete logical hierarchy representing the complete filesystem on the local machine, the LAN and even the WAN. Its advanced functionality exceeds that of the now aging, intrinsic file-handling routines.
Dim oOFS As FileSystemObjectDim oDrive As Drive Set oOFS = New FileSystemObject Set oDrive = oOFS.GetDrive("\\NTWS3\C$") </p>
Dim oFSO As FileSystemObjectDim oFolder As Folder Set oFSO = New FileSystemObject Set oFolder = oFSO.GetSpecialFolder(SystemFolder) </p>
Dim oFSO As FileSystemObject Set oFSO = New FileSystemObject </p>
Dim oFSO As FileSystemObjectDim oFolder As Folder Set oFSO = New FileSystemObject oFSO.MoveFolder("C:\Program Files\Data\", "C:\Archives\") </p>
Dim oFSO As FileSystemObjectDim oFolder As Folder Set oFSO = New FileSystemObject Set oFolder = oFSO.GetFolder("C:\Program Files\Data\") </p>
Dim oFSO As FileSystemObjectSet oFSO = New FileSystemObject If Not oFSO.FileExists("d:\datafiles\newdata.dat") Then MsgBox "The new data file cannot be found" End If </p>
Dim oFSO As FileSystemObjectDim oDrive As Drive Set oFSO = New FileSystemObject Set oDrive = oFSO.GetDrive("\\NTWS3\E$") If oDrive.DriveType = CDRom Then MsgBox "Sorry - can't write to this drive" End If </p>
Dim oFSO As FileSystemObjectDim oDrive As Drive Dim oFolder As Folder Set oFSO = New FileSystemObject Set oDrive = oFSO.GetDrive("\\NTWS3\C$") Set oFolder = oDrive.RootFolder </p>
Dim oFSO As FileSystemObjectDim oDrive As Drive Dim oFolder As Folder Dim oFolders As Folders Set oFSO = New FileSystemObject Set oDrive = oFSO.GetDrive("\\NTWS3\C$") Set oFolder = oDrive.RootFolder Set oFolders = oFolder.SubFolders </p>
Dim oFSO As FileSystemObjectDim oDrive As Drive Dim oFolder As Folder Dim oFiles As Files Set oFSO = New FileSystemObject Set oDrive = oFSO.GetDrive("\\NTWS3\C$") Set oFolder = oDrive.RootFolder Set oFiles = oFolder.Files </p>
Dim oFSO As FileSystemObjectDim oTextStream As TextStream Set oFSO = New FileSystemObject Set oTextStream = oFSO.CreateTextFile("newfile.txt") </p>
Dim oFSO As FileSystemObjectDim oTextStream As TextStream Set oFSO = New FileSystemObject Set oTextStream = oFSO.OpenTextFile("newfile.txt",ForWriting, Create:=True) </p>
Dim oFSO As FileSystemObjectDim oFile As File Set oFSO = New FileSystemObject Set oFile = oFSO.GetFile("c:\data\olddata.dat") Debug.Print oFile.DateLastModified </p>
Dim oFSO As FileSystemObjectDim oTextFile As TextStream Dim sIncomingData As String Set oFSO = New FileSystemObject Set oTextFile = oFSO.OpenTextFile("c:\data\textdata.txt", ForReading) sIncomingData = oTextFile.Read(100) </p>
Dim oFSO As FileSystemObjectDim oTextFile As TextStream Dim sOutgoingData As String sOutgoingData = "Some Text" Set oFSO = New FileSystemObject Set oTextFile = oFSO.OpenTextFile("c:\data\textdata.txt", ForAppending) oTextFile.WriteLine sOutgoingDataBack to Article
Copyright © 1998, Dr. Dobb's Journal