Wie kann man auf einfache Weise eine Datei von einem URL-Pfad herunterladen?
Antworten
Zu viele Anzeigen?Sie können auch die Methode DownloadFileAsync in der WebClient-Klasse verwenden. Sie lädt die Ressource mit dem angegebenen URI in eine lokale Datei herunter. Auch bei dieser Methode wird der aufrufende Thread nicht blockiert.
Beispiel:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
Für weitere Informationen:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
Prüfen Sie, ob eine Netzwerkverbindung besteht, indem Sie GetIsNetworkAvailable()
um zu vermeiden, dass leere Dateien erstellt werden, wenn keine Verbindung zu einem Netzwerk besteht.
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadFileAsync(new Uri("http://www.examplesite.com/test.txt"),
"D:\\test.txt");
}
}
WebClient ist veraltet
Wenn Sie in eine Datei herunterladen möchten, vermeiden Sie es, zuerst in den Speicher zu lesen, indem Sie ResponseHeadersRead
wie diese:
static public async Task HttpDownloadFileAsync(HttpClient httpClient, string url, string fileToWriteTo) {
using HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
using Stream streamToReadFrom = await response.Content.ReadAsStreamAsync();
using Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create);
await streamToReadFrom.CopyToAsync(streamToWriteTo);
}
Der obige Code ist eher eine Skizze, das Hinzufügen einer korrekten Fehler-/Ausnahmebehandlung ist nicht trivial, auch der Fortschrittsbericht ist nicht trivial, ebenso wie das Disposing.
Ich habe eine Reihe von C# 9.0-Erweiterungsklassen für DownoadFileAsync
, GetToStringAsync
y PostToStringAsync
namespace System.Net.Http {
// HttpResponse is in one of 3 states:
// - ResponseMessageInfo is object && ResponseMessageInfo.IsSuccessStatusCode -> success, inspect ResponseMessageInfo for StatusCode etc
// - ResponseMessageInfo is object && !ResponseMessageInfo.IsSuccessStatusCode -> failure, inspect ResponseMessageInfo for StatusCode, ReasonPhrase etc
// - ResponseMessageInfo is null -> exception, inspect ExceptionInfo fields
public record HttpResponse {
// copies of HttpRequestMessage and HttpResponseMessage which do not have the content and do not need to be disposed
public record HttpRequestMessageInfo(HttpRequestHeaders Headers, HttpMethod Method, HttpRequestOptions Options, Uri? RequestUri, Version Version, HttpVersionPolicy VersionPolicy);
public record HttpResponseMessageInfo(HttpResponseHeaders Headers, bool IsSuccessStatusCode, string? ReasonPhrase, HttpRequestMessageInfo RequestMessage, HttpStatusCode StatusCode, HttpResponseHeaders TrailingHeaders, Version Version);
// holds Http exception information
public record HttpExceptionInfo(HttpRequestMessageInfo HttpRequestMessage, string ErrorMessage, WebExceptionStatus? WebExceptionStatus);
// if ResponseMessageInfo is null ExceptionInfo is not and vice versa
public HttpResponseMessageInfo? ResponseMessageInfo { get; init; }
public HttpExceptionInfo? ExceptionInfo { get; init; }
public HttpResponse(HttpRequestMessage requestMessage, HttpResponseMessage responseMessage) {
var requestMessageInfo = new HttpRequestMessageInfo(requestMessage.Headers, requestMessage.Method, requestMessage.Options, requestMessage.RequestUri, requestMessage.Version, requestMessage.VersionPolicy);
ResponseMessageInfo = new(responseMessage.Headers, responseMessage.IsSuccessStatusCode, responseMessage.ReasonPhrase, requestMessageInfo, responseMessage.StatusCode, responseMessage.TrailingHeaders, responseMessage.Version);
ExceptionInfo = null;
}
public HttpResponse(HttpRequestMessage requestMessage, Exception exception) {
ResponseMessageInfo = null;
var requestMessageInfo = new HttpRequestMessageInfo(requestMessage.Headers, requestMessage.Method, requestMessage.Options, requestMessage.RequestUri, requestMessage.Version, requestMessage.VersionPolicy);
if (exception is WebException ex1 && ex1.Status == WebExceptionStatus.ProtocolError) {
using HttpWebResponse? httpResponse = (HttpWebResponse?)ex1.Response;
ExceptionInfo = new(requestMessageInfo, httpResponse?.StatusDescription ?? "", ex1.Status);
}
else if (exception is WebException ex2) ExceptionInfo = new(requestMessageInfo, ex2.FullMessage(), ex2.Status);
else if (exception is TaskCanceledException ex3 && ex3.InnerException is TimeoutException) ExceptionInfo = new(requestMessageInfo, ex3.InnerException.FullMessage(), WebExceptionStatus.Timeout);
else if (exception is TaskCanceledException ex4) ExceptionInfo = new(requestMessageInfo, ex4.FullMessage(), WebExceptionStatus.RequestCanceled);
else ExceptionInfo = new(requestMessageInfo, exception.FullMessage(), null);
}
public override string ToString() {
if (ResponseMessageInfo is object) {
var msg = ResponseMessageInfo.IsSuccessStatusCode ? "Success" : "Failure";
msg += $" {Enum.GetName(typeof(HttpStatusCode), ResponseMessageInfo.StatusCode)}";
if (ResponseMessageInfo.ReasonPhrase is object) msg += $" {ResponseMessageInfo.ReasonPhrase}";
return msg;
} else if (ExceptionInfo is object) {
var msg = "Failure";
msg += $" {ExceptionInfo.ErrorMessage}";
if (ExceptionInfo.WebExceptionStatus is object) msg += $" {Enum.GetName(typeof(WebExceptionStatus), ExceptionInfo.WebExceptionStatus)}";
return msg;
}
return "NA"; // never reach here
}
}
public static class ExtensionMethods {
// progressCallback recieves (bytesRecieved, percent, speedKbSec) and can return false to cancell download
public static async Task<(bool success, HttpResponse httpResponse)> DownloadFileAsync(this HttpClient httpClient, Uri requestUri, string fileToWriteTo, CancellationTokenSource? cts = null, Func<long, int, float, bool>? progressCallback = null) {
var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = requestUri };
var created = false;
try {
var cancellationToken = cts?.Token ?? default;
using HttpResponseMessage httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
if (!httpResponseMessage.IsSuccessStatusCode) return (false, new(httpRequestMessage, httpResponseMessage));
var contentLength = httpResponseMessage.Content.Headers.ContentLength;
using Stream streamToReadFrom = await httpResponseMessage.Content.ReadAsStreamAsync();
using Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create);
created = true;
var buffer = new byte[81920];
var bytesRecieved = (long)0;
var stopwatch = Stopwatch.StartNew();
int bytesInBuffer;
while ((bytesInBuffer = await streamToReadFrom.ReadAsync(buffer, cancellationToken)) != 0) {
await streamToWriteTo.WriteAsync(buffer.AsMemory(0, bytesInBuffer), cancellationToken);
bytesRecieved += bytesInBuffer;
if (progressCallback is object) {
var percent = contentLength is object && contentLength != 0 ? (int)Math.Floor(bytesRecieved / (float)contentLength * 100.0) : 0;
var speedKbSec = (float)((bytesRecieved / 1024.0) / (stopwatch.ElapsedMilliseconds / 1000.0));
var proceed = progressCallback(bytesRecieved, percent, speedKbSec);
if (!proceed) {
httpResponseMessage.ReasonPhrase = "Callback cancelled download";
httpResponseMessage.StatusCode = HttpStatusCode.PartialContent;
return (false, new(httpRequestMessage, httpResponseMessage));
}
}
}
return (true, new(httpRequestMessage, httpResponseMessage));
}
catch (Exception ex) {
if (created) try { File.Delete(fileToWriteTo); } catch { };
return (false, new(httpRequestMessage, ex));
}
}
public static async Task<(string? ResponseAsString, HttpResponse httpResponse)> GetToStringAsync(this HttpClient httpClient, Uri requestUri, CancellationTokenSource? cts = null) {
var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = requestUri };
try {
var cancellationToken = cts?.Token ?? default;
using var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);
if (!httpResponseMessage.IsSuccessStatusCode) return (null, new(httpRequestMessage, httpResponseMessage));
var responseAsString = await httpResponseMessage.Content.ReadAsStringAsync();
return (responseAsString, new(httpRequestMessage, httpResponseMessage));
}
catch (Exception ex) {
return (null, new(httpRequestMessage, ex)); ;
}
}
public static async Task<(string? ResponseAsString, HttpResponse httpResponse)> PostToStringAsync(this HttpClient httpClient, Uri requestUri, HttpContent postBuffer, CancellationTokenSource? cts = null) {
var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = requestUri, Content = postBuffer };
try {
var cancellationToken = cts?.Token ?? default;
using var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);
if (!httpResponseMessage.IsSuccessStatusCode) return (null, new(httpRequestMessage, httpResponseMessage));
var responseAsString = await httpResponseMessage.Content.ReadAsStringAsync();
return (responseAsString, new(httpRequestMessage, httpResponseMessage));
}
catch (Exception ex) {
return (null, new(httpRequestMessage, ex));
}
}
}
}
namespace System {
public static class ExtensionMethods {
public static string FullMessage(this Exception ex) {
if (ex is AggregateException aex) return aex.InnerExceptions.Aggregate("[ ", (total, next) => $"{total}[{next.FullMessage()}] ") + "]";
var msg = ex.Message.Replace(", see inner exception.", "").Trim();
var innerMsg = ex.InnerException?.FullMessage();
if (innerMsg is object && innerMsg!=msg) msg = $"{msg} [ {innerMsg} ]";
return msg;
}
}
}
Zu verwenden:
// download to file
var lastPercent = 0;
bool progressCallback(long bytesRecieved, int percent, float speedKbSec) {
if (percent > lastPercent) {
lastPercent = percent;
Log($"Downloading... {percent}% {speedKbSec/1024.0:0.00}Mbps");
}
return true;
}
var (success, httpResponse) = await httpClient.DownloadFileAsync(
new(myUrlString),
localFileName,
null, // CancellationTokenSource
progressCallback
);
if (success) {
// file downloaded to localFile, httpResponse.ResponseMessageInfo contain
// extra information ie headers and status code
} else {
Log(httpResponse.ToString()); // human friendly error information
// if httpResponse.ResponseMessageInfo is object then server refused the request -
// examine httpResponse.ResponseMessageInfo.HttpStatusCode etc
// else we had a Http exception - examine httpResponse.ExceptionInfo
}
// Http get
var (responseAsString, httpResponse) = await httpClient.GetToStringAsync(url);
if (responseAsString is object) {
// responseAsString contains the string response from the server
} else {
// as for DownloadFileAsync
}
// http post
var postBuffer = new StringContent(jsonInString, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
var (responseAsString, httpResponse) = await httpClient.PostToStringAsync(url, postBuffer);
if (responseAsString is object) {
// responseAsString contains the string response from the server
} else {
Log(httpResponse.ToString()); // human friendly error informaiton
// as for DownloadFileAsync
}
Der folgende Code enthält die Logik zum Herunterladen der Datei mit dem ursprünglichen Namen
private string DownloadFile(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
string filename = "";
string destinationpath = Environment;
if (!Directory.Exists(destinationpath))
{
Directory.CreateDirectory(destinationpath);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result)
{
string path = response.Headers["Content-Disposition"];
if (string.IsNullOrWhiteSpace(path))
{
var uri = new Uri(url);
filename = Path.GetFileName(uri.LocalPath);
}
else
{
ContentDisposition contentDisposition = new ContentDisposition(path);
filename = contentDisposition.FileName;
}
var responseStream = response.GetResponseStream();
using (var fileStream = File.Create(System.IO.Path.Combine(destinationpath, filename)))
{
responseStream.CopyTo(fileStream);
}
}
return Path.Combine(destinationpath, filename);
}