Get original filename when downloading with WebClient

Posted on

Problem :

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?

        WebClient wc= new WebClient();
        var data=   wc.DownloadData(@"www.sometime.comgetfile?id=123");

Using DownloadFile() isn’t a solution since this method needs a filename in advance.

Solution :

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.comgetfile?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(""", """")

Leave a Reply

Your email address will not be published. Required fields are marked *