Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top