Get filename without Content-Disposition

user1854270 picture user1854270 · Nov 26, 2012 · Viewed 13.1k times · Source

I am looking for a solution for this problem for days and I can't find any.

I want to download a file from a webserver with a webclient. The download works fine, but I can't get the real filename, which is very important for me.

I read on many homepages, that the filename should be saved in the Content-Disposition-Header. Unfortunately this header of the site is empty. I tried to get it with:

string header_contentDisposition ="";
using (WebClient client = new WebClient())
            {
                client.OpenRead(link);

                header_contentDisposition = client.ResponseHeaders["Content-Disposition"];
                MessageBox.Show(header_contentDisposition);
            }

There is no information saved inside this header.

If I try to download the file with my Browser (IE, Opera, Chrome) the filename gets shown in the filedialog, so it has to be saved somewhere.

Can you imagine where I can find it?

EDIT: I can't extract it from the URL, because the link is generated by php like

http://www.example.com/download.php?id=10

Answer

Lunyx picture Lunyx · Nov 26, 2012

You can try this:

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        try
        {

            HttpWebResponse res = (HttpWebResponse)request.GetResponse();
            using (Stream rstream = res.GetResponseStream())
            {
                string fileName = res.Headers["Content-Disposition"] != null ?
                    res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
                    res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) : 
                    Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
                    Path.GetFileName(res.ResponseUri.ToString()) : defaultFileName;
            }
            res.Close();
        }
        catch { }

Tested this on http://upload.p-kratzer.com/index.php?dir=&file=asdfasdfwervdcvvedb and it does return wetter.JPG.