redirect file download
September 10th, 2011

Redirect to Stream as File Attachment to Download in ASP.NET

Generally we need to convert stream as file attachment in asp.net to provide export functionality. The main objective is to convert stream as file attachment without creating any file on server side. So I created a common method which takes stream as input and gives as file attachment in response.

Code:

    void StreamToFileAttachment(Stream str, string fileName){       
       byte[] buf = new byte[str.Length];  //declare arraysize
       str.Read(buf, 0, buf.Length); 
        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.AddHeader("Content-Length", str.Length.ToString());
        Response.ContentType = "application/octet-stream";
        Response.OutputStream.Write(buf, 0, buf.Length); 
        Response.End();
    }

How to Use:

See following example to call StreamToFileAttachment method:

FileStream fs = new FileStream(@"C:\techbrij\logo.jpg",FileMode.Open);
StreamToFileAttachment(fs, "TechBrij.jpg");
fs.Close();

Hope, It helps!!!