简体   繁体   中英

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 .

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.

Your link is broken (404), but you might look at this: https://msdn.microsoft.com/en-us/library/system.uri.absolutepath.aspx

Request.Url.AbsolutePath

The AbsolutePath property contains the path information that the server uses to resolve requests for information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM