How to download a file with HttpClient in c#

Microsoft recently released a prelease of HttpClient in a portable library via Nuget. But it seems that many developers do not know how to use it.

Again, the source, for this and a whole bunch of other stuff, is here:

Here’s one way to use it to download a URL and save it to a file: (I am using windows 7, therefore no WindowsRT available to me, so I’m also using System.IO.)

  1. public static class WebUtils
  2.     {
  3.         private static Lazy<IWebProxy> proxy = new Lazy<IWebProxy>(() => string.IsNullOrEmpty(Settings.Default.WebProxyAddress) ? null : new WebProxy { Address = new Uri(Settings.Default.WebProxyAddress), UseDefaultCredentials = true });
  5.         public static IWebProxy Proxy
  6.         {
  7.             get { return WebUtils.proxy.Value; }
  8.         }
  10.         public static Task DownloadAsync(string requestUri, string filename)
  11.         {
  12.             if (requestUri == null)
  13.                 throw new ArgumentNullException(“requestUri”);
  15.             return DownloadAsync(new Uri(requestUri), filename);
  16.         }
  18.         public static async Task DownloadAsync(Uri requestUri, string filename)
  19.         {
  20.             if (filename == null)
  21.                 throw new ArgumentNullException(“filename”);
  23.             if (Proxy != null)
  24.             {
  25.                 WebRequest.DefaultWebProxy = Proxy;
  26.             }
  28.             using (var httpClient = new HttpClient())
  29.             {
  30.                 using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
  31.                 {
  32.                     using (
  33.                         Stream contentStream = await (await httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
  34.                         stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None, Constants.LargeBufferSize, true))
  35.                     {
  36.                         await contentStream.CopyToAsync(stream);
  37.                     }
  38.                 }
  39.             }
  40.         }
  41.     }


Note that I’m saving the address of the proxy server I use (at work) in a setting, and using that if such setting is specified. Otherwise, it should tell you all you need to know regarding using the HttpClient beta to download and save a file.

LargeBufferSize is just a constant I use, for a large buffer (surprise surprise) – you don’t need my source code download for this to make sense. (If you do, you are probably in the wrong career.)

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

3 Responses to How to download a file with HttpClient in c#

  1. mdisibio says:

    Post is a bit old already, but the ‘CopyToAsync’ from http stream to file stream is quite elegant!

    Liked by 1 person

  2. Viktor says:

    Very many thanks for showing file upload code.


  3. Sangamesh Ranjanagi says:

    Thank you very much. This helped a lot.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s