如何从服务器删除下载的文件

时间:2014-02-18 06:49:37

标签: c# asp.net

我创建了一个mdb文件,并使用asp.net压缩该文件,然后我下载了zip文件。

下载文件后,我只想使用c#?

从目录中删除文件

我刚试过,但是按钮点击存在后才完成下载,但是我想下载文件,下载后会从目录中删除。

3 个答案:

答案 0 :(得分:3)

举个例子:

protected virtual void DownloadNDelete(string sFilePath, string sContentType)    
{   

string FileName = Path.GetFileName(sFilePath);
Response.Clear();
Response.AddHeader("Content-Disposition","attachment; filename=" + FileName);
Response.ContentType = sContentType;
Response.WriteFile(sFilePath);
Response.Flush();
this.DeleteFile(sFilePath);
Response.End();

}

答案 1 :(得分:1)

这可能对您有所帮助

String filename=Directory.GetFile(@"c:\filename");
File.Delete(filename);

答案 2 :(得分:1)

您是否尝试过此代码?

string filename = "yourfilename";
if (filename != "")
{
    string path = Server.MapPath(filename);
    System.IO.FileInfo file = new System.IO.FileInfo(path);
    if (file.Exists)
    {
         Response.Clear();
         //Content-Disposition will tell the browser how to treat the file.(e.g. in case of jpg file, Either to display the file in browser or download it)
         //Here the attachement is important. which is telling the browser to output as an attachment and the name that is to be displayed on the download dialog
         Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
        //Telling length of the content..
         Response.AddHeader("Content-Length", file.Length.ToString());

        //Type of the file, whether it is exe, pdf, jpeg etc etc
         Response.ContentType = "application/octet-stream";

        //Writing the content of the file in response to send back to client..
         Response.WriteFile(file.FullName);
         Response.End();

       // Delete the file... 
         System.IO.File.Delete(file.FullName);    

    }
    else
    {
         Response.Write("This file does not exist.");
    }
}