从URL路径下载文件的简单方法是什么?
当前回答
您可能需要在文件下载期间了解状态并更新ProgressBar,或者在发出请求之前使用凭据。
下面是一个包含这些选项的示例。Lambda符号和字符串插值已被使用:
using System.Net;
// ...
using (WebClient client = new WebClient()) {
Uri ur = new Uri("http://remotehost.do/images/img.jpg");
//client.Credentials = new NetworkCredential("username", "password");
String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
client.DownloadProgressChanged += (o, e) =>
{
Console.WriteLine($"Download status: {e.ProgressPercentage}%.");
// updating the UI
Dispatcher.Invoke(() => {
progressBar.Value = e.ProgressPercentage;
});
};
client.DownloadDataCompleted += (o, e) =>
{
Console.WriteLine("Download finished!");
};
client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}
其他回答
包括这个命名空间
using System.Net;
异步下载,并在UI线程本身中放置一个ProgressBar来显示下载的状态
private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync (
// Param1 = Link of file
new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
// Param2 = Path to save
"D:\\Images\\front_view.jpg"
);
}
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
试试这个:
private void downloadFile(string url)
{
string file = System.IO.Path.GetFileName(url);
WebClient cln = new WebClient();
cln.DownloadFile(url, file);
}
如果你需要设置头文件和cookie来下载文件,你需要做一些稍微不同的事情。这里有一个例子……
// Pass in the HTTPGET URL, Full Path w/Filename, and a populated Cookie Container (optional)
private async Task DownloadFileRequiringHeadersAndCookies(string getUrl, string fullPath, CookieContainer cookieContainer, CancellationToken cancellationToken)
{
cookieContainer ??= new CookieContainer(); // TODO: FILL ME AND PASS ME IN
using (var handler = new HttpClientHandler()
{
UseCookies = true,
CookieContainer = cookieContainer, // This will, both, use the cookies passed in, and update/create cookies from the response
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, // use only if it gets angry about the SSL endpoints
AllowAutoRedirect = true,
})
{
using (var client = new HttpClient(handler))
{
SetHeaders(client);
using (var response = await client.GetAsync(getUrl, cancellationToken))
{
if (response.IsSuccessStatusCode)
{
var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
await File.WriteAllBytesAsync(fullPath, bytes, cancellationToken); // This overwrites the file
}
else
{
// TODO: HANDLE ME
throw new FileNotFoundException();
}
}
}
}
}
并且,要添加你需要的header…
private void SetHeaders(HttpClient client)
{
// TODO: SET ME
client.DefaultRequestHeaders.Connection.Add("keep-alive");
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...");
client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9, ...");
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en", .9));
...
}
旁白:你可以通过以下方式填充cookie容器:
循环遍历前一个响应的cookie。 这个响应可以来自HttpAgilityPack,或者WebClient,或者Puppeteer(有很多选项) 手动输入(来自配置值或硬编码值)。
使用System.Net.WebClient.DownloadFile:
string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myStringWebResource = remoteUri + fileName;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource, fileName);
}
使用GetIsNetworkAvailable()检查网络连接,以避免在未连接到网络时创建空文件。
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");
}
}