4

I have the following method available to download a file when a page is visited. The issue have is that it seems to yield files with added bytes back, that based on the type of file can make it corrupt. I have the following method:

Public Class GetImage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'snipped unimportant code
        Dim fileSize = New FileInfo(filepath).Length
        Response.Clear()
        Response.AddHeader("content-length", fileSize.ToString())
        Response.ContentType = "application/octet-stream"
        Response.AppendHeader("content-disposition", "attachment; filename=" & DisplayName)
        Response.TransmitFile(filepath)
    End Sub
End Class

For an example when an xlsm file with the size 177030 is downloaded using the above method the downloaded file has a size of 177710 and becomes corrupt (but repairable) in Excel. It always seems to add 680 bytes.

I've tried substituting TransmitFile with WriteFile. Setting the length in TransmitFile to the actual filesize that is correctly retrieved from FileInfo. I've also looked at different files and I've tried running it both locally on server and locally; all with the same results.

NotFound
  • 5,005
  • 2
  • 13
  • 33
  • Maybe some antivirus/antimalware suite in your PC doesn't like xlsm files? If you just rename it (change extension), does behavior change? What does Fiddler show? If you download this file with wget or curl or similar, what happens? – Arvo May 20 '19 at 10:08
  • @Arvo It was my mistake. I judged it based on reports that specifically mentioned `xlsm` files. At testing I apparently used files that had no issue with the extra bytes added and showed the file without any error. So issue still persist, but it's not related to the type of file (which makes a lot more sense to me now) – NotFound May 20 '19 at 11:28
  • 1
    That makes more sense to me too :) Quick search on topic found eg this: https://stackoverflow.com/questions/14566781/correct-usage-of-asp-net-response-transmitfile-and-response-end/36968241 – Arvo May 20 '19 at 11:39
  • 1
    You shouldn't need Response.Clear() nor Response.AddHeader("content-length"). – Simon Mourier May 20 '19 at 17:57
  • @SimonMourier removed them @Arvo thanks apparently the `Flush` was the missing element; feel free to add it as anwser – NotFound May 21 '19 at 11:48

1 Answers1

0

It was missing Response.Flush() at the end of the method

NotFound
  • 5,005
  • 2
  • 13
  • 33