这是我的代码
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("\"", "");
}
如何在不下载文件的情况下获取文件名,我的意思是不使用client.DownloadData
??
答案 0 :(得分:2)
WebClient不会支持它,但是使用HttpWebRequest,你可以尝试做得很好并在服务器支持时发送HEAD请求,或者如果它没有发送正常的GET请求而且不要下载数据:
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();
如果服务器不支持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();