Get filename without Content-Disposition

前端 未结 1 1752
时光取名叫无心
时光取名叫无心 2021-02-15 07:40

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

1条回答
  •  鱼传尺愫
    2021-02-15 08:20

    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.

    0 讨论(0)
提交回复
热议问题