Created
July 5, 2016 10:02
-
-
Save RAGNOARAKNOS/cc516e380d7ecb505a3cd1e7a897a638 to your computer and use it in GitHub Desktop.
Extend the .NET HTTPContent class (used by HTTPClient) to download files, with usage example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Security.Cryptography; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Basic | |
{ | |
public static class HttpContentExtensions | |
{ | |
public static Task ReadAsFileAsync(this HttpContent content, string filename, bool overwrite) | |
{ | |
string pathname = Path.GetFullPath(filename); | |
if (!overwrite && File.Exists(filename)) | |
{ | |
throw new InvalidOperationException(string.Format("File {0} already exists.", pathname)); | |
} | |
FileStream fileStream = null; | |
try | |
{ | |
fileStream = new FileStream(pathname, FileMode.Create, FileAccess.Write, FileShare.None); | |
return content.CopyToAsync(fileStream).ContinueWith( | |
(copyTask) => | |
{ | |
fileStream.Close(); | |
}); | |
} | |
catch | |
{ | |
if (fileStream != null) | |
{ | |
fileStream.Close(); | |
} | |
throw; | |
} | |
} | |
} | |
public class Program | |
{ | |
static void Main(string[] args) | |
{ | |
RunAsync().Wait(); | |
Console.ReadKey(); | |
} | |
static async Task RunAsync() | |
{ | |
var creds = new NetworkCredential("root", "P@ssw0rd"); | |
var handler = new HttpClientHandler {Credentials = creds}; | |
HttpClient client = new HttpClient(handler); | |
var bytearray = Encoding.ASCII.GetBytes("root:P@ssw0rd"); | |
// Ye olde way of doing authentication pre-dotnet 4.5 | |
//client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytearray)); | |
await client.GetAsync(@"https://esxi/host/license.cfg").ContinueWith( | |
(requestTask) => | |
{ | |
HttpResponseMessage fileHttpResponseMessage = requestTask.Result; | |
fileHttpResponseMessage.EnsureSuccessStatusCode(); | |
fileHttpResponseMessage.Content.ReadAsFileAsync(@"D:\Lic.cfg", true).ContinueWith( | |
(help) => | |
{ | |
Console.Write("A"); | |
}); | |
}); | |
await client.GetAsync(@"https://esxi/host/hostd.log").ContinueWith( | |
(requestTask) => | |
{ | |
HttpResponseMessage fileHttpResponseMessage = requestTask.Result; | |
fileHttpResponseMessage.EnsureSuccessStatusCode(); | |
fileHttpResponseMessage.Content.ReadAsFileAsync(@"D:\hostd.log", true).ContinueWith( | |
(help) => | |
{ | |
Console.Write("B"); | |
}); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment