Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output file from an .aspx page

I'm trying to output a file from my DownloadFile.aspx page using code-behind C# code. I do the following:

protected void Page_Load(object sender, EventArgs e)
{
    string strFilePath = @"C:\Server\file";
    string strFileName = @"downloaded.txt";

    long uiFileSize = new FileInfo(strFilePath).Length;

    using (Stream file = File.OpenRead(strFilePath))
    {
        Response.ContentType = "application/octet-stream";

        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + strFileName + "\"");
        Response.AddHeader("Content-Length", uiFileSize.ToString());

        Response.OutputStream.CopyTo(file);

        Response.End();
    }
}

This works, but when the file is downloaded & saved its contents are just an HTML page.

What am I doing wrong here?

like image 444
ahmd0 Avatar asked Dec 25 '22 22:12

ahmd0


2 Answers

You're copying the streams backward. Should be:

file.CopyTo(Response.OutputStream);
like image 104
Joe Enos Avatar answered Dec 31 '22 12:12

Joe Enos


Clear the response before sending the file, and use the TransmitFile method instead.

    Response.Clear()
    Response.TransmitFile("FilePath.ext")
    Response.End()

http://msdn.microsoft.com/en-us/library/12s31dhy.aspx

like image 24
Oscar Avatar answered Dec 31 '22 12:12

Oscar