Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DownloadService : IDownloadService, IDisposable
- {
- private readonly HttpClient _httpClient;
- private readonly ILogger _logger;
- private bool _disposed;
- public DownloadService(ILogger logger)
- {
- _logger = logger;
- _httpClient = new HttpClient();
- }
- public async Task DownloadAsync(Uri source, string destinationDirectory)
- {
- _logger.LogDebug($"Initiating async file download for {source.AbsoluteUri}");
- try
- {
- using (var request = new HttpRequestMessage(HttpMethod.Get, source))
- {
- using (Stream contentStream = await (await _httpClient.SendAsync(request)).Content.ReadAsStreamAsync(),
- stream = new FileStream($@"{destinationDirectory}\{Path.GetFileName(source.LocalPath)}", FileMode.Create, FileAccess.Write, FileShare.None, 4096, true))
- {
- await contentStream.CopyToAsync(stream);
- }
- }
- }
- catch (Exception ex)
- {
- _logger.LogError($"Error occurred while async downloading {source.AbsoluteUri}", ex);
- throw;
- }
- }
- public void Download(Uri source, string destinationDirectory)
- {
- _logger.LogDebug($"Initiating file download for {source.AbsoluteUri}");
- try
- {
- AsyncHelper.RunSync(() => DownloadAsync(source, destinationDirectory));
- }
- catch (Exception ex)
- {
- _logger.LogError($"Error occurred while downloading {source.AbsoluteUri}", ex);
- throw;
- }
- }
- public void BatchDownload(List<Uri> sources, string destinationDirectory)
- {
- sources.ForEach(source => Download(source, destinationDirectory));
- }
- public Task BatchDownloadAsync(List<Uri> sources, string destinationDirectory)
- {
- Parallel.ForEach(sources, new ParallelOptions { MaxDegreeOfParallelism = 2 }, source =>
- {
- Download(source, destinationDirectory);
- });
- return Task.CompletedTask;
- }
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- protected virtual void Dispose(bool disposing)
- {
- if (_disposed)
- return;
- if (disposing)
- {
- _httpClient?.Dispose();
- }
- _disposed = true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement