【问题标题】:How to download a file from a website in C# [closed]如何从 C# 中的网站下载文件 [关闭]
【发布时间】:2010-10-06 05:42:44
【问题描述】:

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

【问题讨论】:

  • 米奇的评论是最直接最准确的回答,哈哈!
  • 除非您是 .net 新手,否则我建议搜索 MSDN 文档会有所帮助。寻找你想要实现的东西,看看它可能适合的命名空间,看看是否有一个类可以做到这一点:)
  • @shahkalpesh - 见鬼了......只是谷歌:+C#+“下载文件”
  • 这个网站的想法不是告诉人们用谷歌搜索他们的答案,这个网站的想法是让人们问问题,尽管他们有多愚蠢,这样当人们在未来谷歌搜索时就会得到答案就在这里。

标签: c# download windows


【解决方案1】:

WebClient class:

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

【讨论】:

  • 谢谢,这完全符合我的要求!
  • 如何将文件下载到相对于应用程序安装目录的文件夹中? (因为您的下载路径是硬编码的)
  • @Tareck117 AppDomain.CurrentDomain.BaseDirectory + "myname"
  • 有没有办法使用像 Response.BinaryWrite 这样的 webclient 在浏览器中请求保存/打开?
【解决方案2】:

使用WebClient.DownloadFile:

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

【讨论】:

  • SKEEEEEEEEEEEEEEET!
  • 不要忘记 IDisposable ;-p 但是(除了“使用”)这正是我来写的......
  • 在答案中添加异步版本?我不敢编辑飞碟帖子。
  • @JohanLarsson:我认为不值得重温几年前的所有WebClient 答案来显示异步版本。
  • +1 用于 Using 关键字。
【解决方案3】:

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

以下是涵盖这些选项的示例:

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

回调函数实现如下:

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

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

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

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

【讨论】:

  • 如果您想使用async Task 而不是async void,请查看使用await webClient.DownloadFileTaskAsync(...)this answer,因此不需要DownloadDataCompleted 事件
【解决方案4】:

当然,您只需使用HttpWebRequest

一旦您设置了HttpWebRequest,您可以将响应流保存到文件StreamWriterBinaryWriterTextWriter,具体取决于 MIME 类型。)并且您的硬盘上有一个文件开车。

编辑:忘了WebClient。除非您只需要使用GET 来检索您的文件,否则这很有效。如果该网站要求您向其提供POST 信息,则您必须使用HttpWebRequest,所以我将留下我的答案。

【讨论】:

【解决方案5】:

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

using System.Net;

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

【讨论】:

    【解决方案6】:

    试试这个例子:

    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();
    } 
    

    实现如下:

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

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

    【讨论】:

      【解决方案7】:

      您也可以在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/

      【讨论】:

        猜你喜欢
        • 2015-09-28
        • 2016-07-09
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-29
        • 1970-01-01
        相关资源
        最近更新 更多