Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get filename while downloading it

Tags:

c#

download

We are providing files that are saved in our database and the only way to retrieve them is by going by their id as in:

www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23

Everything is working file as I am using the WebClient Class.

There's only one issue that I am facing:

How can I get the real filename?

My code looks like this atm:

WebClient client = new WebClient ();  string url = "www.AwesomeURL.com/AwesomeSite.aspx?requestedFileId=23";  client.DownloadFile(url, "IDontKnowHowToGetTheRealFileNameHere.txt"); 

All I know is the id.

This does not happen when I try accessing url from the browser where it get's the proper name => DownloadedFile.xls.

What's the proper way to get the correct response?

like image 927
Faizan S. Avatar asked Nov 04 '10 13:11

Faizan S.


2 Answers

I had the same problem, and I found this class: System.Net.Mime.ContentDisposition.

using (WebClient client = new WebClient()){     client.OpenRead(url);      string header_contentDisposition = client.ResponseHeaders["content-disposition"];     string filename = new ContentDisposition(header_contentDisposition).FileName;      ...do stuff... } 

The class documentation suggests it's intended for email attachments, but it works fine on the server I used to test, and it's really nice to avoid the parsing.

like image 84
wst Avatar answered Sep 27 '22 19:09

wst


Here is the full code required, assuming the server has applied content-disposition header:

using (WebClient client = new WebClient()) {     using (Stream rawStream = client.OpenRead(url))     {         string fileName = string.Empty;         string contentDisposition = client.ResponseHeaders["content-disposition"];         if (!string.IsNullOrEmpty(contentDisposition))         {             string lookFor = "filename=";             int index = contentDisposition.IndexOf(lookFor, StringComparison.CurrentCultureIgnoreCase);             if (index >= 0)                 fileName = contentDisposition.Substring(index + lookFor.Length);         }         if (fileName.Length > 0)         {             using (StreamReader reader = new StreamReader(rawStream))             {                 File.WriteAllText(Server.MapPath(fileName), reader.ReadToEnd());                 reader.Close();             }         }         rawStream.Close();     } } 

If the server did not set up this header, try debugging and see what ResponseHeaders you do have, one of them will probably contain the name you desire. If the browser show the name, it must come from somewhere.. :)

like image 24
Shadow Wizard Hates Omicron Avatar answered Sep 27 '22 20:09

Shadow Wizard Hates Omicron