简体   繁体   English

如何从C#中的URL获取真实文件名?

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

I want to get the filename from a url for a download manager application. 我想从下载管理器应用程序的URL中获取文件名。 I know to get it using Uri.AbsolutePath or Path.GetFileName but these methods don't give good results for some urls. 我知道要使用Uri.AbsolutePathPath.GetFileName来获取它,但是这些方法对于某些URL不能提供良好的结果。

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. 例如,在此链接中真实名称WinRAR 5.40 Final TR.zip ,但Path.GetFileName将其命名zjESdHoqm?key = 035db62f2375981abf05c615955812a72d5f2701 ,这是一个奇怪的名称。

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#? 所以我想问,有没有一种确切的方法来在C#中获取正确的文件名?

UPDATE: I have figured out the link expires. 更新:我已经知道链接过期。 Sorry for that. 抱歉 But I couldn't any other URL to explain my problem. 但是我没有其他URL可以解释我的问题。

If you want to test my problem, you can renew the url from this page . 如果要测试我的问题,可以从此页面续订URL。

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 您的链接已断开(404),但是您可能会看到此链接: https : //msdn.microsoft.com/zh-cn/library/system.uri.absolutepath.aspx

Request.Url.AbsolutePath Request.Url.AbsolutePath

The AbsolutePath property contains the path information that the server uses to resolve requests for information AbsolutePath属性包含服务器用来解析信息请求的路径信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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