9.4 Manipulating Files from Scripts

One of the myths surrounding the Windows Script Host, and VBScript in particular, is that there's no provision for accessing the filesystem (copying, deleting, and writing to files). This assumption is based on the fact that VBScript, when used in web pages, is not permitted to access the filesystem for security reasons.

The following routines, all of which rely on the FileSystemObject object, should provide most necessary file operations. The names I've chosen for these functions and subroutines are based on what they act upon and what they're used for; for example, the FolderCopy subroutine is used to copy a folder, and the FileCopy subroutine is used to copy a file.

The following two functions return properties of drives whether a specific drive letter exists and how much free space a specified drive has, respectively:

Function DriveExists(DriveLetter)   Set FileObject = CreateObject("Scripting.FileSystemObject")   DriveExists = FileObject.DriveExists(DriveLetter) End Function    Function DriveFreeSpace(DriveLetter)   If Left(DriveLetter,1) <> ":" Then DriveLetter = DriveLetter & ":"   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set DriveHandle = _                  FileObject.GetDrive(FileObject.GetDriveName(DriveLetter))   DriveFreeSpace = DriveHandle.FreeSpace End Function 

These next seven subroutines and functions are used to manipulate folders. The functions are used to retrieve information about a folder, and the subroutines are used to perform actions on a folder. The arguments should all be full folder names (e.g., "D:\Documents and Settings\All Users\Desktop"). Note that the FolderSize function returns the combined size of all the contents of a folder, including all subfolders, and may take a few seconds to return a result for large folders. You may want to use the FolderExists function before any others to prevent errors:

Sub FolderCopy(Source, Destination)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FileObject.CopyFolder Source, Destination End Sub Function FolderCreate(Foldername)   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set Result = FileObject.CreateFolder(FolderName)   If Result.Path = "" Then     FolderCreate = False   'failure   Else     FolderCreate = True    'success   End If End Function Sub FolderDelete(Foldername)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FileObject.DeleteFolder(Foldername) End Sub Function FolderExists(Foldername)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FolderExists = FileObject.FolderExists(Foldername) End Function Sub FolderMove(Source, Destination)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FileObject.MoveFolder Source, Destination End Sub Function FolderSize(Foldername)   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set FolderHandle = FileObject.GetFolder(Foldername)   FolderSize = FolderHandle.Size End Function   Function FolderParent(Foldername)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FolderParent = FileObject.GetParentFolderName(Foldername) End Function

These next seven subroutines and functions are used to manipulate files, and are similar to the folder counterparts listed above. And likewise, the functions are used to retrieve information about a file, and the subroutines are used to perform actions on a file. The arguments should all be fully qualified filenames (e.g., "c:\windows\notepad.exe"). You may want to use the FileExists function before any others to prevent errors:

Sub FileCopy(Source, Destination)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FileObject.CopyFile Source, Destination End Sub Function FileDate(Filename)   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set FileHandle = FileObject.GetFile(Filename)   GetFileDate = FileHandle.DateCreated End Function  Sub FileDelete(Filename)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FileObject.DeleteFile(Filename) End Sub Function FileExists(Filename)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FileExists = FileObject.FileExists(Filename) End Function Function FileExtension(Filename)   Set FileObject = CreateObject("Scripting.FileSystemObject")   GetFileExtension = FileObject.GetExtensionName(Filename) End Function Sub FileMove(Source, Destination)   Set FileObject = CreateObject("Scripting.FileSystemObject")   FileObject.MoveFile Source, Destination End Sub Function FileSize(Filename)   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set FileHandle = FileObject.GetFile(Filename)   FileSize = FileHandle.Size End Function  

This next two functions can be used on either files or folders and allow you to retrieve and set file attributes (Archive, Read-Only, System, and Hidden, respectively).

File attributes are specified numerically: Read-Only = 1, Hidden = 2, System = 4, and Archive = 32. So, to set the Hidden and System attributes for a file, the Attrib parameter would be set to 6 (or 2+4). To read a file's attributes, the same constants are used, but only individually. For example, to see if a file had, say, the System attribute turned on, you would use this statement: If GetAttributes("c:\somefile.txt",4) = True Then Msgbox "This is a system File." :

Function GetAttributes(Filename, Attrib)   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set FileHandle = FileObject.GetFile(Filename)   If FileHandle.Attributes And Attrib Then     GetAttributes = True   Else     GetAttributes = False   End If End Function Sub SetAttributes(Filename, Attrib)   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set FileHandle = FileObject.GetFile(Filename)   FileHandle.Attributes = Attrib End Sub

The following four functions are used to obtain the locations of special Windows folders, or, in the case of GetTempFilename, to generate a new filename in the current user's Temp folder. (Rather than simply returning the location of the Temp folder, the GetTempFilename function returns the full path of a newly-generated temporary filename. The corresponding file is guaranteed not to exist, so you can use it for the purposes of temporary storage without fear of conflicting with another open application.)

So, for example, to get the full path of the current user's Desktop folder, you would use GetSpecialFolder("Desktop"). The folders accessible with this function include AllUsersDesktop, AllUsersStartMenu, AllUsersPrograms, AllUsersStartup, Desktop, Favorites, Fonts, MyDocuments, NetHood, PrintHood, Programs, Recent, SendTo, StartMenu, Startup, and Templates. See Section 9.16 later in this chapter for several examples.

Function GetSpecialFolder(Foldername)   set WshShell = WScript.CreateObject("WScript.Shell")   GetSpecialFolder = WshShell.SpecialFolders(Foldername) End Function Function GetSystemFolder(  )   Set FileObject = CreateObject("Scripting.FileSystemObject")   GetSystemFolder = FileObject.GetSpecialFolder(1) & "\" End Function Function GetTempFilename(  )   Set FileObject = CreateObject("Scripting.FileSystemObject")   GetTempFile = FileObject.GetSpecialFolder(2) & "\" _                 & FileObject.GetTempName End Function Function GetWindowsFolder(  )   Set FileObject = CreateObject("Scripting.FileSystemObject")   GetWindowsFolder = FileObject.GetSpecialFolder(0) & "\" End Function

While the previous functions and subroutines are used to manipulate files, the following two are used to manipulate the contents of files. The ReadFromFile function will transfer the contents of any file into a variable (naturally, this is most useful with plain-text files). Likewise, the WriteToFile subroutine will transfer the contents of a variable (specified as "Text") into a file. If the file doesn't exist, it will be created; if the file already exists, the text will be appended to the end of the file:

Function ReadFromFile(Filename)   Const ForReading = 1, ForWriting = 2, ForAppending = 8   Set FileObject = CreateObject("Scripting.FileSystemObject")   Set FileHandle = FileObject.OpenTextFile(Filename, ForReading)   Buffer=""   Do Until FileHandle.AtEndOfStream     Buffer = Buffer & FileHandle.ReadLine & vbCrLf   Loop   FileHandle.Close   ReadFromFile = Buffer End Function Sub WriteToFile(Filename, Text)   Const ForReading = 1, ForWriting = 2, ForAppending = 8   Set FileObject = CreateObject("Scripting.FileSystemObject")   If FileObject.FileExists(Filename) Then     Set FileHandle = FileObject.OpenTextFile(Filename, _                                              ForAppending)     FileHandle.Write vbCrLf   Else     Set FileHandle = FileObject.CreateTextFile(Filename)   End If   FileHandle.Write Text   FileHandle.Close End Sub

The use of all of the "file operations" subroutines and functions listed earlier should be fairly self-explanatory, and they all work similarly. For example, the FolderExists function and the FileExists function are both nearly identical, except that FolderExists checks for the existence of a folder, while FileExists checks for the existence of a single file. See the Section 9.16.5 example script at the end of this chapter for additional examples, as well as a method for obtaining a list of all the files in a given folder.



Windows XP Annoyances
Fixing Windows XP Annoyances
ISBN: 0596100531
EAN: 2147483647
Year: 2005
Pages: 78
Authors: David A. Karp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net