Copying, Moving, and Deleting Files
Copying, moving, and deleting files are three common file system operations, and all three of these
operations are supported by the FileSystemObject object. Each operation has its own
function, and these are defined as:
CopyFile source, destination[, overwrite]
MoveFile source, destination
DeleteFile FullFilePath[, force]
Note: the default value for the overwrite parameter is True; the
default property for the Force parameter is False.
These are all methods of the FileSystemObject, so when using them in an ASP page, you
must first create an instance of the FileSystemObject object. For example, if we wanted
to copy all of the .htm files in C:\InetPub\wwwroot to the directory C:\windows\desktop, the following code would work:
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile "C:\InetPub\wwwroot\*.htm", "C:\Windows\Desktop"
Set objFSO = Nothing
|
Again, when dealing with these methods, permissions are an important issue. The IUSR_machinename user ID must have write permissions to copy a file from one directory to another.
The MoveFile method is similar to the CopyFile method, except that the
file that is being moved is removed from source and copied to destination.
Therefore, the IUSR_machinename account must have, at minimum delete permissions on the source directory and write permissions on the destination directory.
The DeleteFile method can be used to delete one or more files. The FullFilePath can contain a single file, or consist of multiple files by use of the wildcard character (*). For example, you could delete all of the .asp files in
C:\InetPub\wwwroot by using the following code:
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFile "C:\InetPub\wwwroot\*.asp", False
Set objFSO = Nothing
|
The optional parameter for the DeleteFile method is Force. This defaults to
False, and determines whether or not read-only files will be deleted. Only if
Force is set to True will read-only files be deleted.
The FileSystemObject provides a number of collections that contain information on the drives, directories, and files in the computer's file system. We will look at how to iterate through these collections in the next FAQ!
Happy Programming!
|