简体   繁体   English

如何从Windows窗体中的给定URL下载文件到特定路径?

[英]How to download a file to a specific path in from a given url in a windows form?

我需要使用winforms将指定链接(url)中的pdf文件下载到Windows应用程序中的特定文件夹,任何人都可以建议我使用解决方案。

using System.Net;

using (WebClient webClient = new WebClient())
{
    webClient.DownloadFile("http://mysite.com/myfile.txt", @"c:\myfile.txt");
}

You can use the WebClient.DownloadFile method, available since .NET 2.0. 您可以使用自.NET 2.0以来可用的WebClient.DownloadFile方法。 It is usable from any type of application, not just Winforms. 它可以从任何类型的应用程序中使用,而不仅仅是Winforms。

You should be aware that DownloadFile blocks until the entire file finishes downloading. 您应该知道DownloadFile会阻塞,直到整个文件完成下载。 To avoid blocking you can use the WebClient.DownloadFileAsync method that will download in the background and raise the DownloadFileCompleted event when downloading finishes 为了避免阻塞,您可以使用将在后台下载的WebClient.DownloadFileAsync方法,并在下载完成时引发DownloadFileCompleted事件

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);
myWebClient.DownloadFile(myStringWebResource,fileName); 

If not the Target path is not specified and if you give it like file.abc it is downloaded to a path called Application.StartupPath as the name of file.abc So 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"这样的特定路径@"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提供的示例代码的第一个站点获得它,最后我发现了这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM