Output file from an .aspx page

asp.net, c#, download, web-applications

Solution

You're copying the streams backward. Should be:

file.CopyTo(Response.OutputStream);

Problem

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?

Original source