Search code examples
c#urlfilenames

How to get real filename from a url in C#?


I want to get the filename from a url for a download manager application. I know to get it using Uri.AbsolutePath or Path.GetFileName but these methods don't give good results for some urls.

For example, in this link the realname is WinRAR 5.40 Final TR.zip, but the Path.GetFileName gives it as zjESdHoqm?key=035db62f2375981abf05c615955812a72d5f2701 which is a strange name.

There is also no redirection for this link. It contains the file directly. So I want to ask, Is there an exact way to get the correct filename in C#?

UPDATE: I have figured out the link expires. Sorry for that. But I couldn't any other URL to explain my problem.

If you want to test my problem, you can renew the url from this page.


Solution

  • I have found a good solution for it by myself.

    public static string getFileName(string url)
    {
       HttpWebRequest req = RequestSender.SendRequest(url);
       HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
       string header_contentDisposition = resp.Headers["content-disposition"];
       string escaped_filename = new ContentDisposition(header_contentDisposition).FileName;
    
       return Uri.UnescapeDataString(escaped_filename);
    }
    

    So finally, the filename is correct. Thanks everyone tried to help.