Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())
            {
                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
like image 773
user1854270 Avatar asked Nov 26 '12 18:11

user1854270


1 Answers

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.

like image 103
Lunyx Avatar answered Oct 12 '22 00:10

Lunyx