Question

I have to trigger user downloads of large files to a webbrowser, where I create the file to transfer on the server, then delete it immediately afterwards. I've found enough examples to see that I should probably use Response.TransmitFile or Response.WriteFile... but have heard there are problems with both:

WriteFile is synchronous, but it buffers the file in memory before sending it to the user. Since I'm dealing with very large files, this could cause problems.

TransmitFile doesn't buffer locally so it does work for large files, but it is asynchronous, so I can't delete the file after calling TransmitFile. Apparently flushing the file doesn't guarantee that I can delete it either?

What is the best way of dealing with this?

There is the BinaryWrite also... could I loop through a file stream, copying it in segments?

Was it helpful?

Solution

Here's a good solution which uses TransmitFile but allows you to do something once it's done using a delegate:

http://improve.dk/blog/2008/03/29/response-transmitfile-close-will-kill-your-application

Just replace the logging at the end with file deletion.

OTHER TIPS

WriteFile is synchronous, but it buffers the file in memory before sending it to the user. Since I'm dealing with very large files, this could cause problems.

I believe you can disable the buffering to WriteFile by setting Response.BufferOutput = false;

Once this has been set to false you should be able to call WriteFile without buffering...

Could you commit the file to disk (random name etc), and start sending, but add an entry to a DB table with the Temporary filename, after a Period of time you define, have some cleanup job go through those DB entries, and delete the file from disk if it has aged out.

WriteFile method is used to download the small file from the server,the size parameter must be between zero and the maximum Int32 value, before transferring the file it buffers the file in memory. TransmitFile method is used to download the large file from the server and it does not buffer the file into memory.But when try to delete the file while downloading it then it throws the exception. Below is the code that would delete the file after downloading it.

 FileStream fs = new FileStream(@"D:\FileDownLoad\DeskTop.zip", FileMode.OpenOrCreate);
        MemoryStream ms = new MemoryStream();
        fs.CopyTo(ms);
        context.Response.AppendHeader("content-disposition", "attachment; filename=" + "DeskTop.zip");
        context.Response.ContentType = "application/octet-stream";
        context.Response.BinaryWrite(ms.ToArray());
        fs.Close();
        File.Delete(@"D:\FileDownLoad\DeskTop.zip");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top