ahmd0
ahmd0

Reputation: 17293

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?

Upvotes: 4

Views: 2120

Answers (2)

Oscar
Oscar

Reputation: 13960

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

Upvotes: 3

Joe Enos
Joe Enos

Reputation: 40393

You're copying the streams backward. Should be:

file.CopyTo(Response.OutputStream);

Upvotes: 7

Related Questions