My Technical Notes

Thursday, 31 October 2013

Sending a File to the User in ASP.NET


/// <summary>
/// Send a file to the user.
/// </summary>
/// <param name="fileName">name of the file.</param>
/// <param name="fileBytes">byte array of the bytes of the file.</param>
/// <param name="contentType">e.g. "Application/xlsx", "text/xml" etc.</param>
public void SendFile(string fileName, byte[] fileBytes, string contentType)
{
    Response.BufferOutput = true;
    Response.Buffer = true;
    Response.ContentType = contentType;
    Response.AddHeader("Content-Disposition", "attachment;filename= " + fileName);

    Response.BinaryWrite(fileBytes);
    Response.Flush();
    Response.End();
}

No comments: