A simple Async await call to download a file with Basic Authentication

A simple async await method to download a file using basic authentication. As this is Basic Auth you should only really use it with https:// calls otherwise the username & password will be sent over as plain Base64 string.

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

private static async Task DownloadFileUsingBasicAuth(string url, string saveFileAs, string username, string password)
      HttpClientHandler handler = new HttpClientHandler();
      handler.Credentials = new System.Net.NetworkCredential(username, password);
      HttpClient httpClient = new HttpClient(handler);
      Uri uri = new Uri(url);
      HttpResponseMessage responseMessage = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
      if (responseMessage.StatusCode == HttpStatusCode.OK)
          using (var fileStream = File.Create(saveFileAs))
              using (var httpStream = await responseMessage.Content.ReadAsStreamAsync())


Popular posts from this blog

Switching Xamarin Accounts on Mac and Windows

Xamarin Forms - InitializeComponent does not exist in the current context

How to setup Azure Service Bus Relay to use with ACS