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
is true
by default, you do not need to repeat it. However I'd consider to set it to false
.
- 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 before Response.End()
, it's just redundant.