0

I've stumbled upon this problem recently: In my app, I'm providing users with the option of downloading multiple files from a list by putting them into a .zip folder and then downloading that. I naturally want that .zip folder to be deleted once the download is finished. Here's my approach:

       try {

            Response.Clear();
            Response.ContentType = "application/zip";
            Response.AddHeader("Content-Disposition", "attachment; filename=filename.zip");
            Response.TransmitFile(archive);
            Response.Flush();
            success = success && true;

            return success;

        } catch {

            return false;

        } finally {

            System.IO.File.Delete(archive);
            Response.End();

        }

Now, the booleans are just to indicate whether or not was the download successful and I don't think they are important right now. I thought how this works is the program first tries to transmit the file to the client, if no errors occur it skips the catch block and only after it was downloaded will it delete the archive file.

However, I am often getting an error saying The process cannot access the file because it is being used by another process. on the line System.IO.File.Delete(archive);. This doesn't happen every time, as far as I can see, it's rather random. Could anyone hint me at the solution?

Epsiloney
  • 1
  • 3
  • don't use `Response.TransmitFile` but rather open and send manually the file, also close the connection before you delete the file. – Aristos Aug 16 '16 at 09:24

1 Answers1

0
 Response.ContentType = ContentType;
    Response.AppendHeader("Content-Disposition",
                    "attachment; filename=myFile.txt");
    Response.WriteFile(Server.MapPath("~/uploads/myFile.txt"));
    Response.Flush();
    System.IO.File.Delete(Server.MapPath("~/uploads/myFile.txt"));
    Response.End();
Manish Goswami
  • 863
  • 10
  • 27