Finding information about Files with the WSH

The Windows Scripting Host exposes an object called FileSystemObject. This object has several methods for working with the file system.

Let's see how you can obtain some information about a specific file:

1. Insert a new module into the current VBA project and rename it WSH.

2. In the WSH module, enter the following FileInfo procedure:

Sub FileInfo() Dim fs As Object Dim objFile As Object Dim strMsg As String

Set fs = CreateObject("Scripting.FileSystemObject") Set objFile = fs.GetFile("C:\WINNT\System.ini") strMsg = "File name: " & _ objFile.Name & vbCrLf strMsg = strMsg & "Disk: " & _

objFile.Drive & vbCrLf strMsg = strMsg & "Date Created:" & _

objFile.DateCreated & vbCrLf strMsg = strMsg & "Date Modified:" & _ objFile.DateLastModified & vbCrLf MsgBox strMsg, , "File Information"

End Sub

The FileInfo procedure shown above uses the CreateObject VBA function to create an ActiveX object (FileSystemObject) that is a part of the Windows Scripting library. This object provides access to a computer's file system.

Dim fs As Object

Set fs = CreateObject("Scripting.FileSystemObject")

The above code declares an object variable named fs. Next it uses the CreateObject function to create an ActiveX object and assigns the object to an object variable.

The second line of code in the above procedure:

Set objFile = fs.GetFile("C:\WINNT\System.ini"), creates and returns a reference to the File object for the System.ini file in the C:\WINNT folder and assigns it to the objFile object variable. The File object has many properties that you can read. For example, the statement objFile.Name returns the full name of the file. The statement objFile.Drive returns the drive name where the file is located. The statements obj-File.DateCreated and objFile.DateLastModified return the date the file was created and last modified. This procedure can be easily modified so that it also returns the type of file, its attributes, and the name of the parent folder. Try to modify this procedure on your own by placing within its code the following instructions: objFile.Type, objFile.Attributes, objFile.ParentFolder, and objFile.Size. Check in the Object Browser for what else you can learn about the file by referencing the File object.

0 0

Post a comment