Skip to content

Instantly share code, notes, and snippets.

@jonpryor jonpryor/curl.cs
Last active Jun 19, 2018

Embed
What would you like to do?
// Build with: csc curl.cs -r:System.Net.Http.dll /langversion:7.1
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using TTask = System.Threading.Tasks.Task;
class App {
public static async Task Main (string[] urls)
{
var tasks = new TTask [urls.Length];
using (var client = new HttpClient ()) {
client.Timeout = TimeSpan.FromHours (3);
for (int i = 0; i < urls.Length; ++i) {
tasks [i] = DownloadFile (client, urls [i], Path.Combine (Directory.GetCurrentDirectory(), Path.GetFileName (urls [i])));
}
TTask.WaitAll (tasks);
}
}
static async TTask DownloadFile (HttpClient client, string uri, string destinationFile)
{
if (File.Exists (destinationFile)) {
Console.WriteLine ($"Skipping uri '{uri}' as destination file already exists '{destinationFile}'.");
return;
}
var dp = Path.GetDirectoryName (destinationFile);
var dn = Path.GetFileName (destinationFile);
var tempPath = Path.Combine (dp, "." + dn + ".download");
Directory.CreateDirectory(dp);
Console.WriteLine ($"Downloading `{uri}` to `{tempPath}`.");
try {
using (var s = await client.GetStreamAsync (uri))
using (var o = File.OpenWrite (tempPath)) {
await s.CopyToAsync (o);
}
Console.WriteLine ($"mv '{tempPath}' '{destinationFile}'.");
File.Move (tempPath, destinationFile);
}
catch (Exception e) {
Console.Error.WriteLine ("Unable to download URL `{0}` to `{1}`: {2}", uri, destinationFile, e.Message);
Console.Error.WriteLine (e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.