简体   繁体   English

如何从URL获取文件名而不下载文件C#

[英]how to get filename from URL without downloading file c#

this is my code 这是我的代码

Uri uri = new Uri(this.Url);
var data = client.DownloadData(uri);
if (!String.IsNullOrEmpty(client.ResponseHeaders["Content-Disposition"]))
{
    FileName = client.ResponseHeaders["Content-Disposition"].Substring(client.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", "");
}

how to get the file name without download the file, I mean without using client.DownloadData ?? 如何在不下载文件的情况下获取文件名,我的意思是不使用client.DownloadData

WebClient will not support it but with HttpWebRequest you can either try to be nice and send a HEAD request if the server supports it or if it doesn't send a normal GET request and just don't download the data: WebClient不支持它,但是如果服务器支持它,或者使用HttpWebRequest,您可以尝试变得不错并发送HEAD请求,或者如果它不发送常规的GET请求并且只是不下载数据,则可以:

The HEAD request: HEAD要求:

HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Method = "HEAD";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
string disposition = response.Headers["Content-Disposition"];
string filename = disposition.Substring(disposition.IndexOf("filename=") + 10).Replace("\"", "");
response.close();

If the server doesn't support HEAD, send a normal GET request: 如果服务器不支持HEAD,请发送普通的GET请求:

HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
string disposition = response.Headers["Content-Disposition"];
string filename = disposition.Substring(disposition.IndexOf("filename=") + 10).Replace("\"", "");
response.close();

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

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