Is there any way to get the file extension from a URL

前端 未结 7 1710
再見小時候
再見小時候 2021-02-12 07:04

I want to know that for make sure that the file that will be download from my script will have the extension I want.

The file will not be at URLs like:

h         


        
相关标签:
7条回答
  • 2021-02-12 07:52

    If you just want to get the .jpg part of http://example.com/file.jpg then just use Path.GetExtension as heringer suggests.

    // The following evaluates to ".jpg"
    Path.GetExtension("http://example.com/file.jpg")
    

    If the download link is something like http://example.com/this_url_will_download_a_file then the filename will be contained as part of the Content-Disposition, a HTTP header that is used to suggest a filename for browsers that display a "save file" dialog. If you want to get this filename then you can use the technique suggested by Get filename without Content-Disposition to initiate the download and get the HTTP headers, but cancel the download without actually downloading any of the file

    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();
    
    0 讨论(0)
提交回复
热议问题