Search code examples
c#openxmlfilepathmemorystream

C# Memory Stream/OpenXML sometimes adds extra characters to file name


I export an Excel file using OpenXML and MemoryStream and it sometimes adds extra characters to the file path. It doesn't happen every time. When I first load it up for the day it seems to work just fine, but after running it a bunch it starts to add extra characters. I assume there's a memory leak or buffer problem, but I don't know enough about it to fix it.

My code is:

using (var stream = new MemoryStream())
{                
     report.CreatePackage(stream);

     System.Web.HttpContext.Current.Response.Clear();
     System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
     System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Report_" + DateTime.Now.ToShortDateString() + ".xlsx");
     stream.Position = 0;
     stream.CopyTo(System.Web.HttpContext.Current.Response.OutputStream);
     System.Web.HttpContext.Current.Response.Flush();
     System.Web.HttpContext.Current.Response.Close();
     System.Web.HttpContext.Current.Response.End();
 }  

It will look something like this in the filepath: Report_09_14_2016CAOFMLJL.xlsx instead of just the report and date.

Any help would be appreciated.


Solution

  • On my machine DateTime.Now.ToShortDateString() prints 14/09/2016, I'm guessing it has to do with system settings. Maybe try this instead (or any other formay you require):

    DateTime.Now.ToString("dd_MM_yyyy")
    

    Slashes are not valid in file names on Windows.