Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get original filename when downloading with WebClient

Tags:

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.

like image 528
Tim Dams Avatar asked Dec 10 '13 10:12

Tim Dams


2 Answers

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("\"", ""); } 
like image 149
HaukurHaf Avatar answered Oct 20 '22 08:10

HaukurHaf


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); } 
like image 23
giammin Avatar answered Oct 20 '22 06:10

giammin