0

I have a method to get the filename in server but it doesn't cover all situations. The link below return the filename as attachment;filename=WinRAR.zip;filename*=UTF-8''WinRAR.zip. The correct filename is WinRAR.zip. How to cover all situations to get the correct filename?

string fileName = response.Headers["Content-Disposition"] != null ?
            response.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
            response.Headers["Location"] != null ? Path.GetFileName(response.Headers["Location"]) :
            HttpUtility.UrlDecode(System.IO.Path.GetFileName(response.ResponseUri.ToString()));
Ali Tor
  • 2,772
  • 2
  • 27
  • 58
  • 1
    Don't write the code to parse the Content-Disposition header yourself. Please refer to this answer for how to do it: https://stackoverflow.com/questions/30193569/get-content-disposition-parameters – gerwin Feb 08 '20 at 17:16
  • `string fileName = ContentDispositionHeaderValue.Parse([Header]).FileName;`, if the `Content-Disposition` header is set (no guarantees). The `Location` header is set when you have a redirection, so `HttpStatusCode` is `301`, `302`, `303` (the more common). The `AllowAutoRedirect` feature will follow it. If the FileName is not set and you're asking for a File, you can use the Uri of the request and read the last Segment. If you're asking a Service to send a file (so, no actual name is provided), you have to make one up yourself (based on the current context or whatever) – Jimi Feb 08 '20 at 17:27

0 Answers0