Lädt ein File asynchron von einer Url herunter.
Ihr müsst die Url kennen und Client.
Als Ergebnis erhaltet ihr einen Stream.
public static async Task<Stream> DownloadFileAsync(this HttpClient client, string url, CancellationToken token, IProgress<double> progress = null)
{
var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token);
if (!response.IsSuccessStatusCode)
{
throw new Exception(string.Format("The request returned with HTTP status code {0}", response.StatusCode));
}
var length = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
using (var stream = await response.Content.ReadAsStreamAsync())
{
MemoryStream memoryStream = null;
bool nolength = (length == -1);
int size = ((nolength) ? 8192 : (int)length);
if (nolength)
memoryStream = new MemoryStream();
long total = 0;
int nread = 0;
int offset = 0;
byte[] buffer = new byte[size];
token.ThrowIfCancellationRequested();
while ((nread = await stream.ReadAsync(buffer, offset, size, token)) != 0)
{
if (nolength)
{
memoryStream.Write(buffer, 0, nread);
}
else
{
offset += nread;
size -= nread;
}
total += nread;
if (progress != null)
progress.Report((double)offset);
token.ThrowIfCancellationRequested();
}
return nolength ? memoryStream : new MemoryStream(buffer);
}
Kommentare zum Snippet