user1854270 user1854270 - 11 months ago 133
C# Question

Get filename without Content-Disposition

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())

header_contentDisposition = client.ResponseHeaders["Content-Disposition"];

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

Answer Source

You can try this:

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

            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;
        catch { }

Tested this on and it does return wetter.JPG.