2

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

  • 4
    Possible duplicate of [Get file name from URI string in C#](https://stackoverflow.com/questions/1105593/get-file-name-from-uri-string-in-c-sharp) – Ron Jul 01 '17 at 08:47

1 Answers1

4

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=") + 9).Replace("\"", "");
response.close();
Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41
  • Thank you sir, this is just save my 8 hours of searching before I post this, thanks sir, thank you so much. – Bagus Pradipta Jul 01 '17 at 09:29
  • 1
    Should be `disposition.IndexOf("filename=") + 9` instead of `disposition.IndexOf("filename=") + 10` to prevent possibly cutting off the first character of the file name. – Hakan Yildizhan Sep 27 '22 at 21:24