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?
I had the same problem, and I found this class: System.Net.Mime.ContentDisposition.
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.
You need to look at the
content-disposition
header, via:a typical example would be:
You can use HTTP
content-disposition
header to suggest filenames for the content you are providing:So, in your
AwesomeSite.aspx
script, you would set thecontent-disposition
header. In yourWebClient
class you would retrieve that header to save the file as suggested by yourAwesomeSite
site.I achieve this with the code of wst.
Here is the full code to download the url file in c:\temp folder
Although the solution proposed by Shadow Wizard works well for text files, I needed to support downloading binary files, such as pictures and executables, in my application.
Here is a small extension to
WebClient
that does the trick. Download is asynchronous. Also default value for file name is required, because we don't really know if the server would send all the right headers.Here is the full code required, assuming the server has applied content-disposition header:
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.. :)