3

I have to download an image from a URL to the server with an API controller. I can't use the WebClient.DownloadFile at ASP.NET 5. Is there any other solution?

Thanks in advance!

Adam Radocz
  • 83
  • 1
  • 5

2 Answers2

4

You haven't provided any details why WebClient doesn't work for you, but alternatively you could use the newer HttpClient class:

public static async Task DownloadAsync(Uri requestUri, string filename)
{
    using (var client = new HttpClient())
    using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
    using (
        Stream contentStream = await (await client.SendAsync(request)).Content.ReadAsStreamAsync(),
        stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None, 3145728, true))
    {
        await contentStream.CopyToAsync(stream);
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
4

I think this version is a little bit simpler:

using (var httpClient = new HttpClient())
using (var contentStream = await httpClient.GetStreamAsync(i.SourceUri))
using (var fileStream = new FileStream(fileUploadPath, FileMode.Create, FileAccess.Write, FileShare.None, 1048576, true))
{
    await contentStream.CopyToAsync(fileStream); 
}
Adam Radocz
  • 83
  • 1
  • 5