Search code examples
vb.netcorruptiontransmitfile

TransmitFile yielding a corrupt files with wrong filesize


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.


Solution

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