Search code examples
c#asp.net-mvcfilestream

MVC FileStreamResult is not downloading file with custom file name


The pdf downloads fine but with a random name - 9619012021194536.pdf
I'm trying to set a custom name but it is not working. The downloaded file still has a random name instead of the custom name being set in code.

public ActionResult Appointment(int id)
        {
            Stream stream = null;
            string fileName = "";

            try
            {
                stream = GenerateAppointmentReport(id);
                fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";                    
            }
            catch (Exception ex)
            {
                
            }

            return new FileStreamResult(stream, MimeMapping.GetMimeMapping(fileName))
            { FileDownloadName = fileName };
        }

Solution

  • You can use this code:

    public ActionResult Appointment(int id)
    {
      Stream stream = null;
      string fileName = "";
    
      try
      {
         stream = GenerateAppointmentReport(id);
         fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";                    
      }
      catch (Exception ex)
      {
                        
      }
      return new FileStreamResult(stream, "binary") { FileDownloadName = fileName };
    }
    

    I used this code and the file was downloaded with the specific name I mentioned.