-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloader.cs
More file actions
128 lines (118 loc) · 4.89 KB
/
Downloader.cs
File metadata and controls
128 lines (118 loc) · 4.89 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using System.Security.Policy;
namespace Nexus
{
public partial class Downloader : Form
{
private HttpClient? httpClient;
private CancellationTokenSource? cts;
public string DownloadUrl { get; set; } = string.Empty;
public string SavePath { get; set; } = string.Empty;
public Downloader()
{
InitializeComponent();
}
private async Task DownloadFiles(string downloadUrl, string savePath)
{
if (string.IsNullOrEmpty(downloadUrl))
{
MessageBox.Show("Por favor, insira a URL para download.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
cts = new CancellationTokenSource();
httpClient = new HttpClient();
try
{
using var response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead, cts.Token);
response.EnsureSuccessStatusCode();
long? totalBytes = response.Content.Headers.ContentLength;
long downloadedBytes = 0;
byte[] buffer = new byte[8192];
bool isStreaming = true;
using (var contentStream = await response.Content.ReadAsStreamAsync(cts.Token))
using (var fileStream = new FileStream(savePath!, FileMode.Create, FileAccess.Write, FileShare.None))
{
if (totalBytes.HasValue)
{
ProgressStatus.Maximum = (int)totalBytes.Value;
}
else
{
isStreaming = false;
ProgressStatus.Style = ProgressBarStyle.Marquee; // Indica progresso indeterminado
}
int bytesRead;
while ((bytesRead = await contentStream.ReadAsync(buffer, cts.Token)) > 0)
{
await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cts.Token);
downloadedBytes += bytesRead;
if (totalBytes.HasValue)
{
ProgressStatus.Value = (int)downloadedBytes;
LabelStatus.Text = $"Baixando {(double)downloadedBytes / totalBytes.Value * 100:F2}% ({FormatBytes(downloadedBytes)} / {FormatBytes(totalBytes.Value)})";
}
else if (isStreaming)
{
LabelStatus.Text = $"Baixando {FormatBytes(downloadedBytes)}...";
}
}
}
ProgressStatus.Style = ProgressBarStyle.Continuous; // Restaura o estilo da barra de progresso
LabelStatus.Text = $"Download concluído com sucesso! Salvo em: {savePath}";
}
catch (HttpRequestException ex)
{
MessageBox.Show($"Erro na requisição HTTP: {ex.Message}", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
LabelStatus.Text = "Erro no download.";
if (File.Exists(savePath))
{
File.Delete(savePath);
}
}
catch (TaskCanceledException)
{
LabelStatus.Text = "Download cancelado.";
if (File.Exists(savePath))
{
File.Delete(savePath);
}
}
catch (UriFormatException)
{
MessageBox.Show("A URL inserida é inválida.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
LabelStatus.Text = "URL inválida.";
}
catch (Exception ex)
{
MessageBox.Show($"Ocorreu um erro durante o download: {ex.Message}", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
LabelStatus.Text = "Erro no download.";
if (File.Exists(savePath))
{
File.Delete(savePath);
}
}
finally
{
httpClient?.Dispose();
httpClient = null!;
cts?.Dispose();
cts = null!;
}
}
private static string FormatBytes(long bytes)
{
string[] suffixes = { "B", "KB", "MB", "GB", "TB" };
int i;
double dblSByte = bytes;
for (i = 0; i < suffixes.Length && bytes >= 1024; i++, bytes /= 1024)
{
dblSByte = bytes / 1024.0;
}
return string.Format("{0:0.##} {1}", dblSByte, suffixes[i]);
}
private async void Downloader_Load(object sender, EventArgs e)
{
TextUrl.Text = DownloadUrl;
await DownloadFiles(DownloadUrl, SavePath);
}
}
}