简体   繁体   中英

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 ??

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:

The HEAD request:

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:

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();

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