Last active
June 19, 2018 18:13
-
-
Save jonpryor/dd74692b388191a1a625a0639010a2f4 to your computer and use it in GitHub Desktop.
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
// 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