WriteFile vs TransmitFile for large files that must be deleted from the server after transfer

I have to start the user uploading large files to a web browser, where I create a file for transfer on the server and then delete it immediately after that. I found enough examples to see that I should probably use Response.TransmitFile or Response.WriteFile ... but heard that there are problems with both:

WriteFile is synchronous, but it loads the file into memory before sending it to the user. Since I am dealing with very large files, this can cause problems.

TransmitFile does not load locally, so it works for large files, but it is asynchronous, so I cannot delete the file after calling TransmitFile. Obviously flushing the file does not guarantee that I can delete it?

What is the best way to handle this?

There is also BinaryWrite ... Can I skip a file stream by copying it in segments?

+5
source share
4 answers

Here's a good solution that uses a TransmitFile but allows you to do something when it is executed using a delegate:

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

Just replace the log at the end by deleting the file.

+4
source

WriteFile , . , .

, WriteFile, Response.BufferOutput = false;

false, WriteFile ...

+2

( ..) , , - , , .

0

The WriteFile method is used to download a small file from the server; the size parameter must be between zero and the maximum value of Int32; before transferring the file, it buffers the file in memory. The TransmitFile method is used to download a large file from the server, and it does not hold the file in memory. But when you try to delete a file while it is downloading, it throws an exception. Below is the code that will 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");
0
source

All Articles