如何从 C# 中的 URL 下载文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/307688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to download a file from a URL in C#?
提问by vbroto
What is a simple way of downloading a file from a URL path?
从 URL 路径下载文件的简单方法是什么?
回答by vbroto
Use System.Net.WebClient.DownloadFile
:
使用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);
}
回答by Raj Kumar
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}
回答by petrzjunior
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
回答by turgay
Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.
您也可以在 WebClient 类中使用 DownloadFileAsync 方法。它将具有指定 URI 的资源下载到本地文件。此外,此方法不会阻塞调用线程。
Sample:
样本:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
For more information:
想要查询更多的信息:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
回答by Sayka
Include this namespace
包括这个命名空间
using System.Net;
Download Asynchronouslyand put a ProgressBarto show the status of the download within the UI Thread Itself
异步下载并放置一个ProgressBar来显示UI线程本身内的下载状态
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;
}
回答by haZya
Check for a network connection using GetIsNetworkAvailable()
to avoid creating empty files when not connected to a network.
检查网络连接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");
}
}
回答by Jonas_Hess
Complete class to download a file while printing status to console.
完成类以在将状态打印到控制台时下载文件。
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
class FileDownloader
{
private readonly string _url;
private readonly string _fullPathWhereToSave;
private bool _result = false;
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(0);
public FileDownloader(string url, string fullPathWhereToSave)
{
if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
if (string.IsNullOrEmpty(fullPathWhereToSave)) throw new ArgumentNullException("fullPathWhereToSave");
this._url = url;
this._fullPathWhereToSave = fullPathWhereToSave;
}
public bool StartDownload(int timeout)
{
try
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(_fullPathWhereToSave));
if (File.Exists(_fullPathWhereToSave))
{
File.Delete(_fullPathWhereToSave);
}
using (WebClient client = new WebClient())
{
var ur = new Uri(_url);
// client.Credentials = new NetworkCredential("username", "password");
client.DownloadProgressChanged += WebClientDownloadProgressChanged;
client.DownloadFileCompleted += WebClientDownloadCompleted;
Console.WriteLine(@"Downloading file:");
client.DownloadFileAsync(ur, _fullPathWhereToSave);
_semaphore.Wait(timeout);
return _result && File.Exists(_fullPathWhereToSave);
}
}
catch (Exception e)
{
Console.WriteLine("Was not able to download file!");
Console.Write(e);
return false;
}
finally
{
this._semaphore.Dispose();
}
}
private void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Console.Write("\r --> {0}%.", e.ProgressPercentage);
}
private void WebClientDownloadCompleted(object sender, AsyncCompletedEventArgs args)
{
_result = !args.Cancelled;
if (!_result)
{
Console.Write(args.Error.ToString());
}
Console.WriteLine(Environment.NewLine + "Download finished!");
_semaphore.Release();
}
public static bool DownloadFile(string url, string fullPathWhereToSave, int timeoutInMilliSec)
{
return new FileDownloader(url, fullPathWhereToSave).StartDownload(timeoutInMilliSec);
}
}
Usage:
用法:
static void Main(string[] args)
{
var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
Console.WriteLine("Done - success: " + success);
Console.ReadLine();
}
回答by Kreshnik
You may need to know the status and update a ProgressBar during the file download or use credentials before making the request.
您可能需要在文件下载期间了解状态并更新 ProgressBar,或者在发出请求之前使用凭据。
Here it is, an example that covers these options. Lambda notationand String interpolationhas been used:
这是一个涵盖这些选项的示例。使用了 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");
}
回答by Darshit Gandhi
Below code contain logic for download file with original name
下面的代码包含具有原始名称的下载文件的逻辑
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);
}
回答by Surendra Shrestha
Try using this:
尝试使用这个:
private void downloadFile(string url)
{
string file = System.IO.Path.GetFileName(url);
WebClient cln = new WebClient();
cln.DownloadFile(url, file);
}