Monday, September 22, 2003

Delete file (ASP)

Delete file using ASP JScript (pass filename on in form [hidden input called 'deletefile'] or QueryString [page.asp?deletefile=myfile.doc]):

<%
// delete file
var oFSO = Server.CreateObject("Scripting.FileSystemObject");
// get path to file (relative to current document)
sPathToFile = Server.MapPath("/path/to/upload/folder/"+Request("deletefile"));
// if file exists, delete it 
if(oFSO.FileExists(sPathToFile)) oFSO.DeleteFile(sPathToFile)
// file deleted
%>
Or using ASP VBScript
<%
' delete file
Dim oFSO, sPathToFile
Set oFSO = Server.CreateObject("Scripting.FileSystemObject")
' get path to file (relative to current document)
sPathToFile = Server.MapPath("/path/to/upload/folder/"&Request("deletefile"));
' if file exists, delete it 
If oFSO.FileExists(sPathToFile) Then oFSO.DeleteFile(sPathToFile)
' file deleted
%>

N.B. Folder must have modify permissions set for the Internet Guest Account (normally IUSR_MACHINENAME)

1 comment:

Paul said...

Thank you, thank you, thank you! I cannot say thank you enough. I have been pulling out my hair trying to get the FileExists method to use a relative path. With your help, I had Server.MapPath("relative path") populate my var, and then everything worked like a charm! Thanks again :)