ASP.NET Delete file after exception in TransmitFile

2

I have following code:

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

Everything works fine, only when user cancels download I get:

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.

Is only way to delete orphaned files is to try to delete old (for example hour old) files? How long system will keep lock (GoDaddy shared hosting)? Thank you.

asp.net
asked on Stack Overflow Aug 25, 2011 by Mateusz

2 Answers

3

1) I think you should put context.Response.Flush() after TransmitFile() as you want to make sure that the file have been streamed to the client before you go on deleting the file.

2) TransferFile() is also streaming the file without buffering it in memory. This will lock the file while it's in use. You might want to load it to memory and use Response.OutputStream instead.

answered on Stack Overflow Aug 25, 2011 by Muttok
0

I have moved from GoDaddy to Arvixe (reason: huge problems in sending emails), changed code and till now everything works fine (when successful and interrupted download):

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();
}
answered on Stack Overflow Aug 27, 2011 by Mateusz

User contributions licensed under CC BY-SA 3.0