什么是从URL路径下载文件的简单方法?如何从C#中的URL下载文件?
回答
使用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);
}
using (var client = new WebClient())
{
client.DownloadFile("http://example.com/file/song/a.mpeg", "a.mpeg");
}
有史以来最好的解决方案,但我想添加一个重要的行'client.Credentials = new NetworkCredential(“UserName”,“Password”);' – 2016-09-07 13:11:13
一个受欢迎的副作用:这种方法也支持本地文件作为第一个参数 – copa017 2017-08-22 08:35:51
using System.Net;
WebClient webClient = new WebClient();
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
欢迎来到SO!通常,对已经有高度回应的现有旧问题发布低质量答案并不是一个好主意。 – ThiefMaster 2013-06-29 16:25:39
我从seanb的评论中找到了我的答案,但是我确实比其他人更喜欢这种“低质量”的答案。它是完整的(使用语句),简洁易懂。作为一个老问题是无关紧要的,恕我直言。 – Josh 2013-12-30 19:50:49
您也可以在WebClient类使用DownloadFileAsync方法。它使用指定的URI将资源下载到本地文件。此方法也不会阻塞调用线程。
样品:
webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
欲了解更多信息:
http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/
包括这个命名空间
using System.Net;
下载异步并把进度显示在UI中的下载的状态线程本身
private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync(new System.Uri("http://www.sayka.in/downloads/front_view.jpg"),
"D:\\Images\\front_view.jpg");
}
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
检查使用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");
}
}
在控制台打印状态时下载文件的完整类。
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);
}
}
用法:
static void Main(string[] args)
{
var success = FileDownloader.DownloadFile(fileUrl, fullPathWhereToSave, timeoutInMilliSec);
Console.WriteLine("Done - success: " + success);
Console.ReadLine();
}
而是下载此本地文件,你可以转换为字节流对象和存储在SQL Server中的VARBINARY(MAX)BLOB。
鉴于你的表如下所示:
CREATE TABLE [dbo].[Documents](
[DocumentId] [int] IDENTITY(1,1) NOT NULL,
[DocumentTypeId] [int] NOT NULL,
[UploadedByMemberId] [int] NOT NULL,
[DocumentTitle] [nvarchar](200) NOT NULL,
[DocumentDescription] [nvarchar](2000) NULL,
[FileName] [nvarchar](200) NOT NULL,
[DateUploaded] [datetime] NOT NULL,
[ApprovedForUsers] [bit] NOT NULL,
[ApprovedByMemberId] [int] NOT NULL,
[ApprovedDate] [datetime] NULL,
[DocBLOB] [varbinary](max) NOT NULL,
CONSTRAINT [PK_Documents] PRIMARY KEY CLUSTERED
(
[DocumentId] ASC
)
SqlParameter Title = new SqlParameter("@Title", SqlDbType.VarChar);
SqlParameter FileName = new SqlParameter("@FileName", SqlDbType.VarChar);
SqlParameter DateFileUploaded = new SqlParameter("@DateUploaded", SqlDbType.VarChar);
SqlParameter DocBLOB = new SqlParameter("@DocBLOB", SqlDbType.VarBinary);
command.Parameters.Add(Title);
command.Parameters.Add(FileName);
command.Parameters.Add(DateFileUploaded);
command.Parameters.Add(DocBLOB);
myStringWebResource = remoteUri + dataReader["FileName"].ToString();
imgdownload = myWebClient.DownloadData(myStringWebResource);
querySQL = @"INSERT INTO Documents(DocumentTypeId, UploadedByMemberId, DocumentTitle, DocumentDescription, FileName, DateUploaded, ApprovedForUsers, ApprovedByMemberId, ApprovedDate, DocBLOB) VALUES(1, 0, @Title, '', @FileName, @DateUploaded, 1, 0, GETDATE(), @DocBLOB);";
Title.Value = dataReader["Title"].ToString().Replace("'", "''").Replace("\"", "");
FileName.Value = dataReader["FileName"].ToString().Replace("'", "''").Replace("\"", "");
DateFileUploaded.Value = dataReader["DateUploaded"].ToString();
DocBLOB.Value = imgdownload;
command.CommandText = querySQL;
command.ExecuteNonQuery();
您可能需要知道的状态和文件下载时更新进度或提出请求之前使用的凭据。
这是一个涵盖这些选项的示例。 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");
}
下面的代码包含下载文件的逻辑与原来的名称
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);
}
尝试使用这样的:
private void downloadFile(string url)
{
string file = System.IO.Path.GetFileName(url);
WebClient cln = new WebClient();
cln.DownloadFile(url, file);
}
- 1. 如何从浏览器中的C中的URL下载文件?
- 2. 如何从URL文件名,而无需下载文件c#
- 3. 从变量URL下载文件c#
- 4. 如何从http URL下载文件
- 5. Java - 如何从URL下载文件
- 6. 从URL URL的PHP curl下载文件
- 7. Maven:从url下载文件
- 8. 从URL下载Python文件
- 9. 从url下载pdf文件
- 10. 从url下载文件ColdFusion
- 11. 从url下载mp3文件
- 12. 如何从C#网站下载文件?
- 13. 下载文件Qt中从URL
- 14. 从C#中的给定URL下载文件
- 15. 从wcf c中的URL下载zip文件#
- 16. 如何从node.js中的url下载pdf文件?
- 17. 如何从node.js中的URL同步下载文件
- 18. 如何从python中的下载url获取文件描述符?
- 19. 如何使用phonegap从android中的URL下载文件?
- 20. 从更改的URL下载Excel文件
- 21. 从给定的URL下载文件
- 22. 从blackberry的url下载pdf文件?
- 23. 从URL下载最新的文件
- 24. C#从URL下载图片
- 25. 如何在Node.js中从URL下载音频文件?
- 26. 如何从url下载文件? (不在浏览器中打开)
- 27. 如何从URL下载文件并将其保存在Rails中?
- 28. 如何在PHP中从URL下载多个文件?
- 29. 如何在Python中从url下载文件
- 30. 如何在android中从url下载.docx文件?
看一看在System.Net。WebClient – seanb 2008-11-21 03:00:58