2014-02-18 80 views
0

我已經創建了一個mdb文件,並使用asp.net壓縮該文件,之後我正在下載zip文件。如何刪除從服務器下載的文件

下載文件後,我只想通過使用c#刪除目錄中的文件?

我剛剛嘗試過,但下載是在按鈕單擊存在後完成的,但我想下載該文件,下載後將其從目錄中刪除。

+0

能否請你展示一些代碼? – Ofiris

回答

1

這可能會幫助你

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

您是否嘗試過這個代碼?

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."); 
    } 
} 
+0

點擊按鈕後文件會下載,我把這個代碼放在哪裏? – user3077239

+0

此代碼僅適用於刪除文件。你說你的文件正在被正確下載。所以在下載代碼之後,寫下這段代碼。根據您的文件名更改文件名。 –

+0

我更新了我的代碼以下載和刪除。試試這個代碼。 –

2

有一個例子:

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(); 

} 
+0

Is there任何需要獲取方法DeleteFile的參考。 – user3077239

+0

它需要'mscorlib.dll'根據http://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx,你必須下載該文件: ) – SMI