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?
You're copying the streams backward. Should be:
file.CopyTo(Response.OutputStream);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With