如何在C#中从网站下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/525364/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:46:05  来源:igfitidea点击:

How to download a file from a website in C#

c#downloadwindows

提问by S3THST4

Is it possible to download a file from a website in Windows Application form and put it into a certain directory?

是否可以从网站以 Windows 应用程序形式下载文件并将其放入某个目录?

采纳答案by CMS

With the WebClient class:

使用WebClient 类

using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");

回答by Jon Skeet

Use WebClient.DownloadFile:

使用WebClient.DownloadFile

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
                        @"c:\Users\Jon\Test\foo.txt");
}

回答by FlySwat

Sure, you just use a HttpWebRequest.

当然,您只需使用HttpWebRequest.

Once you have the HttpWebRequestset up, you can save the response stream to a file StreamWriter(Either BinaryWriter, or a TextWriterdepending on the mimetype.) and you have a file on your hard drive.

一旦你的HttpWebRequest设置,您可以响应流保存到一个文件中StreamWriter(无论是BinaryWriter,还是TextWriter取决于媒体类型。),你有你的硬盘驱动器上的文件。

EDIT: Forgot about WebClient. That works good unless as long as you only need to use GETto retrieve your file. If the site requires you to POSTinformation to it, you'll have to use a HttpWebRequest, so I'm leaving my answer up.

编辑:忘记了WebClient。除非您只需要GET用来检索文件,否则效果很好。如果该站点要求您提供POST信息,则必须使用HttpWebRequest,因此我将不做回答。

回答by angelo

Try this example:

试试这个例子:

public void TheDownload(string path)
{
  System.IO.FileInfo toDownload = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path));

  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.AddHeader("Content-Disposition",
             "attachment; filename=" + toDownload.Name);
  HttpContext.Current.Response.AddHeader("Content-Length",
             toDownload.Length.ToString());
  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.WriteFile(patch);
  HttpContext.Current.Response.End();
} 

The implementation is done in the follows:

实现如下:

TheDownload("@"c:\Temporal\Test.txt"");

Source: http://www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html

来源:http: //www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html

回答by turgay

Also you can use DownloadFileAsyncmethod in WebClientclass. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

你也可以DownloadFileAsyncWebClient课堂上使用方法。它将具有指定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 Pouya

You can use this code to Download file from a WebSite to Desktop:

您可以使用此代码将文件从网站下载到桌面:

using System.Net;

WebClient client = new WebClient ();
client.DownloadFileAsync(new Uri("http://www.Address.com/File.zip"), Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "File.zip");

回答by Kreshnik

You may need to know the status during the file download or use credentials before making the request.

在发出请求之前,您可能需要了解文件下载期间的状态或使用凭据。

Here is an example that covers these options:

这是一个涵盖这些选项的示例:

Uri ur = new Uri("http://remotehost.do/images/img.jpg");

using (WebClient client = new WebClient()) {
    //client.Credentials = new NetworkCredential("username", "password");
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword"));
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";

    client.DownloadProgressChanged += WebClientDownloadProgressChanged;
    client.DownloadDataCompleted += WebClientDownloadCompleted;
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg");
}

And the callback's functions implemented as follows:

回调函数实现如下:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
}

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    Console.WriteLine("Download finished!");
}

(Ver 2) - Lambda notation: other possible option for handling the events

(Ver 2) - Lambda 表示法:处理事件的其他可能选项

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) {
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
});

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){
    Console.WriteLine("Download finished!");
});

(Ver 3) - We can do better

(Ver 3) - 我们可以做得更好

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
{
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);

    // updating the UI
    Dispatcher.Invoke(() => {
        progressBar.Value = e.ProgressPercentage;
    });
};

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{
    Console.WriteLine("Download finished!");
};

(Ver 4) - Or

(Ver 4) - 或

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!");
};