[Previous] [Table of Contents] [Next]

File Handling

In this section, I'll describe a few programming techniques that you'll find useful for handling files and folders.

Checking Whether a File or Folder Exists

To check whether a file exists, you can use the FileExists method of the FileSystemObject object:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Autoexec.bat") Then 
    

If the file exists, FileExists returns the value True.

You can check for the presence of a folder by using the FolderExists method:

Set fso = WScript.CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(path)) Then
    

For more information, see the section "Accessing Files and Folders" in Chapter 12.

Checking Whether a Folder is Empty

To check whether a folder is empty, you can use the following code sequence:

Function FolderEmpty(path)
    ' Check for an empty folder.
    Dim fso, oFolder, oFiles         ' Object variables
    Dim i, flag

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set oFolder = fso.GetFolder(path)   ' Get folder.
    Set oFiles = oFolder.Files          ' Get Files collection.

    flag = True                         ' No files
    For Each i in oFiles                ' A file has been found if
        flag = false                    ' the loop is processed.
        Exit For
    Next

    FolderEmpty = flag                  ' Return result.
End Function

If the folder is empty, FolderEmpty returns the value True. For more information, see the section titled "Accessing Files and Folders" in Chapter 12.

Checking Whether an Access Database Is in Use

To access a Microsoft Access database and ensure that the .mdb file isn't open in another Access session, you can use the test for an existing file. When Access 97 opens a database, it automatically produces an .ldb file. This file disappears as soon as Access releases the database. You can check for the existence of an .ldb file to determine whether the database is already in use. The program in Listing 14-12 checks whether an .mdb file is available in the folder and then checks whether the .ldb file exists. It displays the result in a dialog box.

Listing 14-12 MDBOpen.vbs

'**************************************************
' File:    MDBOpen.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born
'
' Checking whether an Access 97 database is in use
'**************************************************
Option Explicit

Dim fso, path, txt

' Get path to database file.
' Must be stored here in the script's folder.
path = WScript.ScriptFullName
path = Left(path, InStrRev(path, "\"))

txt = "Database file doesn't exist"
Set fso = WScript.CreateObject("Scripting.FileSystemObject")

If (fso.FileExists(path & "Test1.mdb")) Then ' Exists?
    If (fso.FileExists(path & "Test1.ldb")) Then
        txt = "Database locked by Access"
    Else
        txt = "Database not locked"
    End If
End If

WScript.Echo txt

'*** End

NOTE
You should copy both MDBOpen.vbs and the Access 97 database Test1.mdb from the \WSHDevGuide\Chapter14 folder to a local folder to conduct the test. This test also works with Access 2000.

Copying a File

You use the File object to copy a file. After you create the FileSystemObject object, you can access the file by using the GetFile method and the Copy method, as shown here:

Set fso = CreateObject("Scripting.FileSystemObject")
Set fi = fso.GetFile(file1)      ' Create file object.
fi.Copy file2                    ' Copy file1 to file2.

NOTE
For more information about files and folders, see Chapter 12.

Renaming a File or Folder

You can use the File object to rename a file by using the following code:

Set fso = CreateObject("Scripting.FileSystemObject")
Set oFile = fso.GetFile("C:\Test.txt") ' Create File object.
oFile.Name = "Test1.txt"               ' Assign a new name.

After the File object is retrieved, the Name attribute is set to the new name.

You can rename a folder in a similar way:

Set fso = CreateObject("Scripting.FileSystemObject")
Set oFolder = fso.GetFolder("C:\Test") ' Create Folder object.
oFolder.Name = "Test1"                 ' Assign a new name.

After the Folder object is retrieved, the Name attribute is set to the new name. Alternatively, you can use the Move method of the FileSystemObject object, as shown in the VBScript sample in Listing 14-13. This sample converts the name of a given file system object to lowercase. The user can drag files or folders to the LCase.vbs file. All dragged file system objects are then shown in lowercase.

Listing 14-13 LCase.vbs

'***************************************************
' File:    LCase.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born
'
' Converting the names of folders or files to lower
' case. The script supports drag and drop.
'***************************************************
Option Explicit

' Set the case direction for the module. Changing
' the value of xCase to false forces the script to convert
' to lowercase.
'Const xCase = True  ' We want to convert to uppercase.
Const xCase = False ' We want to convert to lowercase.
Const Title = "Lowercase converter - by G. Born"

Dim objArgs, param, i

' Try to retrieve the arguments.
Set objArgs = WScript.Arguments    ' Create object.
If objArgs.Count < 1 Then  ' No argument at all. Quit with a dialog box.
    MsgBox "Sorry, no arguments found!" & vbCRLF & _
           "Please drag file(s) or folder(s) to the script's icon.", _
           vbInformation + vbOKOnly, Title
    WScript.Quit  ' Quit script!!!
End If

i = 0
' Try to convert the file to lowercase; count each action.
For Each param In objArgs
    If MakeCase(param, xCase) Then i = i + 1
Next

MsgBox i & " object(s) converted", vbInformation + vbOKOnly, Title
 
Function MakeCase(file, caseFlag)
    Dim fso, oFile, path, name
    Set fso = CreateObject("Scripting.FileSystemObject")

    If fso.FileExists(file) Then
        Set oFile = fso.GetFile(file)
    Else
        If fso.FolderExists(file) Then
            Set oFile = fso.GetFolder(file)
        Else
            MakeCase = False   ' No file system object
            Exit Function
        End If
    End If

    name = fso.GetFileName(file)
    path = fso.GetParentFolderName(file)

    If caseFlag Then
        oFile.Move path & "\" & UCase(name)
    Else
        oFile.Move path & "\" & LCase(name)
    End If
    Set fso = Nothing
    MakeCase = True
End Function

'*** End

NOTE
You can convert LCase.vbs to create uppercase file or folder names. You simply change the value for xCase from False to True. For more information about files and folders, see Chapter 12.

Searching for a File

To search for a file, you can use the FileSystemObject object and its subobjects and methods to retrieve a folder and its subfolders. You must hand-write code to process the folder's content and search for the requested files. To retrieve a list of the occurrences of a given file, use the Run method to execute the MS-DOS DIR command, as shown here:

DIR filename /s > List.txt

You can then access the List.txt file by using the TextStream object and its methods.

Listing All Shortcut Files

I've created a small VBScript program to get the names and locations of all shortcut (.lnk) files contained in the special folders (Desktop, Start menu, and so on). It retrieves the names of the special folders by using the SpecialFolders property that returns a collection object. You can use the items in this collection object to retrieve the Files collection contained in the folder.

To check whether a file is a shortcut, you can use the following statement:

InStrRev(UCase(name), ".LNK")

The function returns the value <> 0 if the filename extension is .lnk. The program in Listing 14-14 searches the special folders for .lnk files and lists the results in a browser window (Figure 14-6).

Click to view at full size.

Figure 14-6 A list of shortcut files

Listing 14-14 ListShortcuts.vbs

'****************************************************
' File:    ListShortcuts.vbs (WSH sample in VBScript) 
' Author:  (c) G. Born
'
' Listing all shortcut files in the special folders
'****************************************************
Option Explicit

Const Title = "Shortcut files"
Dim WshShell
Dim fso, fi, fc, f
Dim text, sysf, fldr

set WshShell = WScript.CreateObject("WScript.Shell")

set fso = WScript.CreateObject("Scripting.FileSystemObject")

text = ""
For Each sysf in WshShell.SpecialFolders
    text = text & "<b>Shortcuts in: " & sysf & "</b><br>"
    Set fldr = fso.getfolder(sysf)
    Set fc = fldr.files
    For Each f In fc
        If IsLnk(f) Then text = text &  f & "<br>"
    Next
    text = text & "<br>"
Next

ShowMSIE text, Title    ' Show item list in browser window.

' Helper function
Function IsLnk(name)
    ' Check whether file is an .lnk file.
    IsLnk = (InStrRev(UCase(name), ".LNK") <> 0)
End Function

Sub ShowMSIE(txt, title)
    Dim oIE, oDoc
    ' Create Internet Explorer Application object.
    Set oIE = WScript.CreateObject("InternetExplorer.Application")
    ' Set browser window properties.
    oIE.left = 20                ' Window position
    oIE.top = 50                 ' and other properties
    oIE.height = 380
    oIE.width = 580
    oIE.menubar = 0              ' No menu
    oIE.toolbar = 0
    oIE.statusbar = 0
    oIE.navigate("about:blank")  ' Create an empty HTML document.
    oIE.visible = 1              ' Keep Internet Explorer visible.
 
    Do While(oIE.Busy): Loop     ' Important: Wait until Internet 
                                 ' Explorer is ready. 
 
    Set oDoc = oIE.Document      ' Get Document object.
    oDoc.open                    ' Open document.
                                 ' Write script to the document object.
    oDoc.writeln("<html><head><title>" & title & "</title></head>")
    oDoc.writeln("<body>" & txt & "</body></html>")
    oDoc.close                   ' Close document for write access.
End Sub

'*** End