Is there any way to know the original name of a file you download using the WebClient when the Uri doesn't contain the name?
This happens for example in sites where the download originates from a dynamic page where the name isn't known beforehand.
Using my browser, the file gets the orrect name. But how can this be done using the WebClient? E.g.
WebClient wc= new WebClient(); var data= wc.DownloadData(@"www.sometime.com\getfile?id=123");
Using DownloadFile() isn't a solution since this method needs a filename in advance.
You need to examine the response headers and see if there is a content-disposition header present which includes the actual filename.
WebClient wc = new WebClient(); var data= wc.DownloadData(@"www.sometime.com\getfile?id=123"); string fileName = ""; // Try to extract the filename from the Content-Disposition header if (!String.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"])) { fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 9).Replace("\"", ""); }
Read the Response Header "Content-Disposition"
with WebClient.ResponseHeaders
It should be:
Content-Disposition: attachment; filename="fname.ext"
your code should look like:
string header = wc.ResponseHeaders["Content-Disposition"]??string.Empty; const string filename="filename="; int index = header.LastIndexOf(filename,StringComparison.OrdinalIgnoreCase); if (index > -1) { fileName = header.Substring(index+filename.Length); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With