ASP: Scripting.FileSystemObject... how to move, copy and delete a file or a folder
The Scripting.FileSystemObject object is very handy when dealing with files or folders on the server. Imagine to have an asp page displaying the content of a folder, the user will be able to manage the folder and its content quite easily.
The FileSystemObject allow to access all information regarding a file (creation date, size, name and so on) and to execute simple operations on the file itself.
Ok, in this post I will concentrate on move, copy and delete operations, but in the future I plan to explore other methods.
First of all we initialize the object:
Now we actually can manipulate the file the way we want.
In order to copy the file, we use:
The CopyFolder method will copy the folder and the CreateFolder method will create a new folder.
Just as reminder, in this post we saw:
the Server.CreateObject("Scripting.FileSystemObject") object,
the CopyFile, CopyFolder, MoveFile, MoveFolder, DeleteFile and DeleteFolder methods.
Now start planning your file management system web page.
The FileSystemObject allow to access all information regarding a file (creation date, size, name and so on) and to execute simple operations on the file itself.
Ok, in this post I will concentrate on move, copy and delete operations, but in the future I plan to explore other methods.
First of all we initialize the object:
<%
Dim FSO
Set FSO= Server.CreateObject("Scripting.FileSystemObject")
Then we set the file we need to manipulate:Dim file
Dim destinationfile
Dim filepath
Dim destinationfilepath
filepath = yourfilepath
destinationfilepath = youdestinationfilepath
file = Server.MapPath(filepath)
destinationfile = Server.MapPath(destinationfilepath)
The yourfilepath and youdestinationfilepath should be something like /fileupload/uploads/763/document1.doc Now we actually can manipulate the file the way we want.
In order to copy the file, we use:
FSO.CopyFile file, destinationfile, False
The last parameter is set to false if you don't want to overwrite an existing file in destination and true if you want to.The CopyFolder method will copy the folder and the CreateFolder method will create a new folder.
Dim folder
Dim newfolder
folder = Server.MapPath("/fileupload/oldfolder/")
newfolder = Server.MapPath("/fileupload/newfolder/")
FSO.CreateFolder newfolder
FSO.CopyFolder folder, newfolder, False
The MoveFile and MoveFolder methods work the same way:FSO.MoveFile file, destinationfile
FSO.MoveFolder folder, newfolder
The easiest methods (but the most dangerous!) are the DeleteFile and DeleteFolder:FSO.DeleteFile file
FSO.DeleteFolder folder
In the end of our little piece of code, we set the object to nothing:Set FSO = Nothing
%>
And that's it.Just as reminder, in this post we saw:
the Server.CreateObject("Scripting.FileSystemObject") object,
the CopyFile, CopyFolder, MoveFile, MoveFolder, DeleteFile and DeleteFolder methods.
Now start planning your file management system web page.