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.
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.
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.. :)
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