-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClientService.cs
More file actions
46 lines (36 loc) · 1.45 KB
/
HttpClientService.cs
File metadata and controls
46 lines (36 loc) · 1.45 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
using HtmlCompiler.Core.Interfaces;
namespace HtmlCompiler.Core;
public class HttpClientService : IHttpClientService
{
public HttpClientService()
{
}
/// <inheritdoc />
public async Task<string> GetAsync(Uri uri)
{
using HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
/// <inheritdoc />
public async Task DownloadFileAsync(Uri uri, string targetFilePath, Action<long, long> progressCallback)
{
using HttpClient client = new();
using HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
await using Stream streamToReadFrom = await response.Content.ReadAsStreamAsync();
long totalBytes = response.Content.Headers.ContentLength ?? -1;
long bytesRead = 0;
byte[] buffer = new byte[8192];
int read;
using Stream streamToWriteTo = File.Open(targetFilePath, FileMode.Create);
while ((read = await streamToReadFrom.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await streamToWriteTo.WriteAsync(buffer, 0, read);
bytesRead += read;
// Fortschritt mithilfe des Callbacks melden
progressCallback?.Invoke(bytesRead, totalBytes);
}
}
}