I've been looking at some code done in C# ASP .NET WebForms and for some reason I really don't like the below code. What is the best alternative for creating a document and downloading it in Webforms, on the click of a button? Should the developer be messing with the Response at all, in this way?
Response.ClearContent();
Response.BufferOutput = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", string.Format("attachment; filename={0:yyyyMMdd}.xlsx", DateTime.Now));
Response.BinaryWrite(pck.GetAsByteArray());
Response.Flush();
Response.End();
1 Answer 1
Yes, in ASP.NET WebForms you don't have any nice helper method to hide this. However if you do it often you should make it easier and less error-prone.
public static void WriteDownload(this HttpResponse response, string fileName, byte[] data)
{
if (String.IsNullOrWhiteSpace(fileName))
throw new ArgumentException("File name must be specified.", "fileName");
if (data == null)
throw new ArgumentNullException("data");
response.ClearContent();
response.ContentType = MimeMapping.GetMimeMapping(fileName);
response.AddHeader("content-disposition",
String.Format("attachment; filename={0}", fileName));
response.BinaryWrite(data);
response.End();
}
It will then be used like this:
Response.WriteDownload(GetFileNameFromTodayDate(".xlsx"), pkg.GetAsByteArray());
Where GetFileNameFromTodayDate()
is simply:
private static string GetFileNameFromTodayDate(string extension)
{
return String.Format("{0:yyyyMMdd}.{1}",
DateTime.Now, extension.TrimStart(' ', '.');
}
Few more notes:
BufferOutput
istrue
by default, you do not need to repeat it. However I'd consider to set it tofalse
.- If you're using .NET Framework 4.5+ you do not need any function to resolve MIME type otherwise you'd better to resort some helper function but do not hard-code it anywhere.
- You do not need
Response.Flush()
because buffering is on and, moreover, you do not stream anything else beforeResponse.End()
, it's just redundant.