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

前端 未结 3 659
北恋
北恋 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:35

    It's possible to get the filename since the server is sending the Content-Disposition header. Here's a code example on how to get the filename using the HttpClient class:

    var url = "http://findicons.com/icon/download/235456/internet_download/128/png?id=235724";
    
    using (var client = new HttpClient())
    using (var response = await client.GetAsync(url))
    {
        // make sure our request was successful
        response.EnsureSuccessStatusCode();
    
        // read the filename from the Content-Disposition header
        var filename = response.Content.Headers.ContentDisposition.FileName;
    
        // read the downloaded file data
        var stream = await response.Content.ReadAsStreamAsync();
    
        // Where you want the file to be saved
        var destinationFile = Path.Combine("C:\\local\\directory", filename);
    
        // write the steam content into a file
        using (var fileStream = File.Create(destinationFile))
        {
            stream.CopyTo(fileStream);
        }
    }
    

提交回复
热议问题