3

Passed parameters are:

`C:\Licenses\testfolder\PERSONAL-Wednesday 04 July-0405.txt`,`c2license.txt`

And the function is:

/// <summary>
/// Starts serving the download
/// </summary>
public static void InitStoreDownload(string filePath, string serveFileName)
{
    // Get size of file
    var f = new FileInfo(filePath);

    var fileSize = f.Length;
    var extension = f.Extension;

    var context = HttpContext.Current;

    context.Response.Clear();
    context.Response.Buffer = false;

    // Correct mime type
    if (extension.Equals(".zip", StringComparison.CurrentCultureIgnoreCase))
        context.Response.ContentType = "application/octet-stream";
    else if (extension.Equals(".txt", StringComparison.CurrentCultureIgnoreCase))
    {
        context.Response.ContentType = "text/plain";
    }

    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + serveFileName);
    context.Response.AddHeader("Content-Length", fileSize.ToString());
    context.Response.TransmitFile(filePath);
    context.Response.Close();

    context.Response.End();
}

The C:\Licenses\testfolder\PERSONAL-Wednesday 04 July-0405.txt file on the server is 475 bytes long.

The file downloaded when fetched with this script is 474 bytes, missing a single byte off the end of the file. (The last byte is a full stop, present on the file on the server but not present when downloaded through this function). This causes the file to become invalid.

We're scratching our heads trying to work out why a byte is missing, could anyone help?

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456

1 Answers1

3

Try to use

Response.TransmitFile(filePath);
HttpContext.Current.ApplicationInstance.CompleteRequest(); 

instead of

Response.Close();
Response.End();

Or as other mentioned:

call Flush() before Close()

Response.TransmitFile(filePath);
Response.Flush();
Response.Close();
Response.End();

or omit the call of Close() and call End() directly cause it includes flushing the Response.

Response.TransmitFile(filePath);
Response.End();

There´s a thread about Response.End() maybe it contains useful information for you.

Community
  • 1
  • 1
Jehof
  • 34,674
  • 10
  • 123
  • 155
  • Still serves 474 bytes, not 475. – Tom Gullen Jul 04 '12 at 13:35
  • @TomGullen - Try `Response.Flush()` before you call `Close()` and `End()` – KV Prajapati Jul 04 '12 at 13:36
  • `Flush` and `CompleteRequest` seem to be the winning combo, thanks guys! Anyone know why this includes the last byte when before it doesn't? – Tom Gullen Jul 04 '12 at 13:40
  • Because `Response.Close` just nukes the connection before the output buffer got a chance to finish emptying. Ironically if you had just called `Response.End` on its own it probably would have worked, as it includes a `Flush`. – Jon Grant Jul 04 '12 at 13:51