C# 如何从 Windows 表单中的给定 url 将文件下载到特定路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9096078/
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 to a specific path in from a given url in a windows form?
提问by Arun Kumar
I need to download pdf files from a specified links(url) to a specific folder in a windows application using winforms please any one can suggest me with a solution.
我需要使用 winforms 将 pdf 文件从指定的链接(url)下载到 Windows 应用程序中的特定文件夹,请任何人都可以向我建议解决方案。
回答by Viper
using System.Net;
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
}
回答by Christoffer
You could just "search the web" (aka google) for "C# download file", and end up with this simple MSDN example(modified to fit your specific question):
您可以“搜索网络”(又名谷歌)以获取“C# 下载文件”,并最终得到这个简单的 MSDN 示例(修改为适合您的特定问题):
string remoteUri = "http://www.test.com/somefile.pdf";
string fileName = "c:\targetfolder\somefile.pdf";
WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(remoteUri,fileName);
回答by Panagiotis Kanavos
You can use the WebClient.DownloadFilemethod, available since .NET 2.0. It is usable from any type of application, not just Winforms.
您可以使用自 .NET 2.0 起可用的WebClient.DownloadFile方法。它可用于任何类型的应用程序,而不仅仅是 Winforms。
You should be aware that DownloadFile blocks until the entire file finishes downloading. To avoid blocking you can use the WebClient.DownloadFileAsyncmethod that will download in the background and raise the DownloadFileCompletedevent when downloading finishes
您应该知道 DownloadFile 会阻塞,直到整个文件完成下载。为避免阻塞,您可以使用WebClient.DownloadFileAsync方法,该方法将在后台下载并在下载完成时引发DownloadFileCompleted事件
回答by diyoda_
myWebClient.DownloadFile(myStringWebResource,fileName);
If not the Target path is not specified and if you give it like file.abcit is downloaded to a path called Application.StartupPathas the name of file.abcSo you just have to give your specific path like @"C:\\Folder1\\Folder2\\file.abc"
如果不是,则未指定目标路径,并且如果您将其file.abc下载到名为Application.StartupPath名称的路径中,file.abc那么您只需要提供您的特定路径,例如@"C:\\Folder1\\Folder2\\file.abc"
I think this will help a bit more. I could not get it at first site of sample codes provided by MSDN and at last i found this.
我认为这会有所帮助。我无法在 MSDN 提供的示例代码的第一个站点上获得它,最后我找到了它。

