Last active
November 25, 2023 17:30
-
-
Save MarcusOtter/b9b4ee3fc7be04469fd20480daa86c38 to your computer and use it in GitHub Desktop.
A complement to https://stackoverflow.com/a/59167167/10615308
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
using System; | |
using System.IO; | |
using System.Threading.Tasks; | |
using System.Net.Http; | |
namespace Example | |
{ | |
public interface IImageDownloader | |
{ | |
Task DownloadImageAsync(string directoryPath, string fileName, Uri uri); | |
} | |
public class ImageDownloader : IImageDownloader, IDisposable | |
{ | |
private bool _disposed; | |
private readonly HttpClient _httpClient; | |
public ImageDownloader(HttpClient httpClient = null) | |
{ | |
_httpClient = httpClient ?? new HttpClient(); | |
} | |
/// <summary> | |
/// Downloads an image asynchronously from the <paramref name="uri"/> and places it in the specified <paramref name="directoryPath"/> with the specified <paramref name="fileName"/>. | |
/// </summary> | |
/// <param name="directoryPath">The relative or absolute path to the directory to place the image in.</param> | |
/// <param name="fileName">The name of the file without the file extension.</param> | |
/// <param name="uri">The URI for the image to download.</param> | |
public async Task DownloadImageAsync(string directoryPath, string fileName, Uri uri) | |
{ | |
if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } | |
// Get the file extension | |
var uriWithoutQuery = uri.GetLeftPart(UriPartial.Path); | |
var fileExtension = Path.GetExtension(uriWithoutQuery); | |
// Create file path and ensure directory exists | |
var path = Path.Combine(directoryPath, $"{fileName}{fileExtension}"); | |
Directory.CreateDirectory(directoryPath); | |
// Download the image and write to the file | |
var imageBytes = await _httpClient.GetByteArrayAsync(uri); | |
await File.WriteAllBytesAsync(path, imageBytes); | |
} | |
public void Dispose() | |
{ | |
if (_disposed) { return; } | |
_httpClient.Dispose(); | |
GC.SuppressFinalize(this); | |
_disposed = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment