-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileDownloader.cs
More file actions
85 lines (80 loc) · 3.14 KB
/
Copy pathFileDownloader.cs
File metadata and controls
85 lines (80 loc) · 3.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace FileDownloader
{
class FileDownloader
{
public string UrlsFile { get; set; }
public string DownloadFolder { get; set; }
public FileDownloader(string urlsFile, string downloadFolder)
{
UrlsFile = urlsFile;
DownloadFolder = downloadFolder;
Directory.CreateDirectory(DownloadFolder);
}
/*
Get all the links in the UrlsFile and start
downloading them one by one and save into the
Download folder as the default folder.
*/
public void DownloadAll()
{
string[] urls = File.ReadAllLines(UrlsFile);
int remainingFiles = urls.Length;
using (WebClient client = new WebClient())
{
Stopwatch sw = new Stopwatch();
client.DownloadProgressChanged += (sender, e) =>
{
if (e.ProgressPercentage > 0 && sw.Elapsed.TotalSeconds > 0)
{
double bytesPerSecond = e.BytesReceived / sw.Elapsed.TotalSeconds;
double secondsRemaining = (e.TotalBytesToReceive - e.BytesReceived) / bytesPerSecond;
Console.Write("\rDownloading {0}: {1}% ({2:0.0} seconds remaining) ", e.UserState, e.ProgressPercentage, secondsRemaining);
}
};
client.DownloadFileCompleted += (sender, e) =>
{
Console.WriteLine("\rDownload of {0} completed.", e.UserState);
remainingFiles--;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("{0} files remaining.", remainingFiles);
Console.ResetColor();
};
foreach (string url in urls)
{
string fileName = Path.GetFileName(url);
string filePath = Path.Combine(DownloadFolder, fileName);
sw.Restart();
client.DownloadFileAsync(new Uri(url), filePath, fileName);
while (client.IsBusy) { }
sw.Stop();
}
}
}
/*
Get the name of the download folder and
rename the default one to the name user
have entered.
*/
public void RenameDownloadFolder()
{
string ?newFolderName = null;
while (string.IsNullOrWhiteSpace(newFolderName))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("What would you like to name the download folder? ");
Console.ResetColor();
newFolderName = Console.ReadLine().Trim();
}
string newFolderPath = Path.Combine(Directory.GetCurrentDirectory(), newFolderName);
Directory.Move(DownloadFolder, newFolderPath);
DownloadFolder = newFolderPath;
}
}
}