| Answer: |
To delete a file from the Web server's file system via an ASP.NET Web page, simply use the File.Delete() method. This method takes a single string input parameter that specifies the physical path to the file that you want to delete. For example, the following code will delete the file C:\MyFiles\SomeFile.xml from the Web server's file system:
' VB.NET File.Delete("C:\MyFiles\SomeFile.xml")
// C# File.Delete("C:\\MyFiles\\SomeFile.xml");
|
(Note that in the C# code you need to escape the backslashes by using two backslashes in succession.)
The File class is located in the System.IO namespace, meaning that you will have to import this namespace into your ASP.NET Web page or code-behind class. If you are using a server-side script block in your ASP.NET Web page, add <%@ Import Namespace="System.IO" %> to the top of the ASP.NET Web page. If you are using a code-behind class, add the following:
' VB.NET Imports System.IO
// C# using System.IO;
|
Realize that in order to be able to successfully delete the specified file, the account used by the ASP.NET engine must have adequate permission to delete the file from the specified directory. Consult THIS FAQ for more information on how to provide the appropriate permissions needed for the appropriate ASP.NET accounts. Also, note that the Delete() method expects the physical path of the file to delete. Realize that you can easily translate a virtual path, like /files/SomeFile.aspx to its corresponding physical path, say C:\InetPub\wwwroot\files\SomeFile.aspx using the Server.MapPath() method. For more information on Server.MapPath() be sure to read Using Server.MapPath. |