2011-08-25 80 views
2

我有以下代碼:ASP.NET刪除文件

try 
{ 
    context.Response.TransmitFile(savedFileName); 
} 
catch (Exception ex) 
{ 
    ExceptionUtility.LogException(new Exception("Exception while transmit zip [AttachmentsSecurityHandler.cs]: " + ex.Message), false); 
} 
finally 
{ 
    try 
    { 
     Thread.Sleep(500); 
     File.Delete(savedFileName); 
    } 
    catch (Exception ex) 
    { 
     ExceptionUtility.LogException(new Exception("Unable to delete temp zip file [AttachmentsSecurityHandler.cs]: " + ex.Message), false); 
    } 
} 

一切正常,只有當用戶取消下載我得到:

Exception while transmit zip [AttachmentsSecurityHandler.cs]: The remote host closed the connection. The error code is 0x800703E3. 
Unable to delete temp zip file [AttachmentsSecurityHandler.cs]: The process cannot access the file 'D:\Hosting\***\html\attachments\tempCompressed\b9b5c47e-86f9-4610-9293-3b92dbaee222' because it is being used by another process. 

只刪除孤立的文件方式是試圖刪除舊的(例如一個小時)文件?系統將鎖定多長時間(GoDaddy共享主機)?謝謝。

回答

3

1)我想你應該在TransmitFile()之後放置context.Response.Flush(),以確保在繼續刪除文件之前,文件已經傳輸到客戶端。

2)TransferFile()也是流式傳輸文件而不緩存在內存中。這將在文件被使用時鎖定文件。您可能想要將其加載到內存中,而是使用Response.OutputStream。

+0

感謝您的回答。我試過了,沒有區別。我使用context.Response.Buffer = false;和context.Response.BufferOutput = false;文件可能很大,所以我不想將文件內容放入內存中。正如我之前所說 - 代碼很好,當用戶不取消下載。 – Mateusz

0

我從GoDaddy的搬到Arvixe(原因:在發送電子郵件巨大的問題),改代碼現在爲止一切正常(如果成功,中斷下載):

try 
{ 
    context.Response.TransmitFile(savedFileName); 
} 
catch (Exception ex) 
{ 
    ExceptionUtility.LogException(new Exception("Exception while transmit zip [AttachmentsSecurityHandler.cs]: " + ex.Message), false); 
} 
finally 
{ 
    byte attemptsCounter = 0; 

    Thread deletingThread = new Thread(delegate() 
     { 
      while (attemptsCounter < 5) 
      { 
       Thread.Sleep(5000); 
       try 
       { 
        File.Delete(savedFileName); 
        break; 
       } 
       catch (Exception ex) 
       { 
        attemptsCounter++; 
        ExceptionUtility.LogException(new Exception(string.Format("Unable to delete temp zip file [AttachmentsSecurityHandler.cs] (attempt {0}): {1}", attemptsCounter, ex.Message)), false); 
       } 
      } 
     }); 

    deletingThread.Start(); 
}