How can i download a file without file name and file extension in the url

前端 未结 3 702
北恋
北恋 2021-01-27 00:14

My problem is that I dont Know how i can download a File withknowing the file name or the file extension in the url, like this http://findicons.com/icon/download/235456/internet

3条回答
  •  死守一世寂寞
    2021-01-27 00:34

    You could inspect the Content-Disposition response header using an HTTP request to get the filename. This would be a more general solution, so even if the filename is not contained in the URL, it would work:

    var url = "http://findicons.com/icon/download/235456/internet_download/128/png?id=235724";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        var fn = response.Headers["Content-Disposition"].Split(new string[] { "=" }, StringSplitOptions.None)[1];
        string basePath = @"X:\Folder\SubFolder"; // Change accordingly...
        var responseStream = response.GetResponseStream();
        using (var fileStream = File.Create(Path.Combine(basePath, fn)))
        {
            responseStream.CopyTo(fileStream);
        }
    }
    

    The above code uses certain methods and functions, you can find more information here:

    • HttpWebRequest - Usage example here
    • Saving a stream to a file - see this answer. Just note that when saving an HTTP response stream, you don't need to seek to the beginning, as it already is at the beginning and doing so will throw an exception. So, to be on the safe side, use it like I have in the code above.

    Hope this answer helps you :)

提交回复
热议问题