Get filename without Content-Disposition

前端 未结 1 1535
名媛妹妹
名媛妹妹 2021-02-15 07:54

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:34

    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)
提交回复
热议问题