Best way to download a file using HttpClient


public async Task DownloadAsync()
{
    using (HttpClient client = new HttpClient())
    {
        string url = "https://github.com/App-vNext/Polly/archive/master.zip";
        using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
        using (Stream fromStream = await response.Content.ReadAsStreamAsync())
        {
            string targetFilename = Path.GetTempFileName();
            using (Stream targetStream = File.Open(targetFilename, FileMode.Create))
            {
                await fromStream.CopyToAsync(targetStream);
            }
        }
    }
}

Comments

Popular posts from this blog

How to add custom header in swagger operation