ASP.NET在传输文件中出现异常后删除文件

ASP.NET在传输文件中出现异常后删除文件,asp.net,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 {

我有以下代码:

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共享主机)?谢谢。

1)我认为您应该将context.Response.Flush()放在TransmitFile()之后,因为您希望在继续删除文件之前确保该文件已流式传输到客户端


2) TransferFile()也在传输文件,而不在内存中缓冲。这将在文件使用时锁定该文件。您可能希望将其加载到内存中,并改用Response.OutputStream。

我已从GoDaddy迁移到Arvixe(原因:发送电子邮件时存在巨大问题),更改了代码,直到现在一切正常(下载成功且中断时):

试试看
{
context.Response.TransmitFile(savedFileName);
}
捕获(例外情况除外)
{
LogException(新异常(“传输zip时异常[AttachmentsSecurityHandler.cs]:”+ex.Message),false);
}
最后
{
字节attemptsconter=0;
线程删除线程=新线程(委托()
{
while(尝试搜索<5)
{
睡眠(5000);
尝试
{
File.Delete(savedFileName);
打破
}
捕获(例外情况除外)
{
attemptsCounter++;
ExceptionUtility.LogException(新异常(string.Format(“无法删除临时zip文件[AttachmentsSecurityHandler.cs](尝试{0}):{1}”,AttemptsCenter,ex.Message)),false);
}
}
});
deletingThread.Start();
}

谢谢您的回答。我已经试过了,没有区别。我使用context.Response.Buffer=false;和context.Response.BufferOutput=false;文件可能相当大,所以我不想将文件内容放入内存。正如我前面所说的,当用户不取消下载时,代码工作得很好。
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();
}