如何从C#网站下载文件

时间:2009-02-08 07:52:24

标签: c# download windows

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

7 个答案:

答案 0 :(得分:109)

使用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");

答案 1 :(得分:78)

使用WebClient.DownloadFile

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

答案 2 :(得分:18)

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

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

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

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

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

答案 3 :(得分:13)

当然,您只需使用HttpWebRequest

设置HttpWebRequest后,您可以将响应流保存到文件StreamWriterBinaryWriterTextWriter,具体取决于mimetype。)并且你的硬盘上有一个文件。

编辑:忘记了WebClient。只要你只需要使用GET来检索你的文件,那就行得很好。如果该网站要求您提供POST信息,则必须使用HttpWebRequest,因此我将离开我的答案。

答案 4 :(得分:2)

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

using System.Net;

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

答案 5 :(得分:0)

试试这个例子:

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

答案 6 :(得分:0)

您也可以在DownloadFileAsync课程中使用WebClient方法。它将具有指定URI的资源下载到本地文件。此方法也不会阻止调用线程。

样品:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

有关详情:

  

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/