windows 如何用C#从网站下载文件[已关闭]

ifmq2ha2  于 2023-11-21  发布在  Windows
关注(0)|答案(7)|浏览(167)

已关闭。此问题需要更多focused。目前不接受回答。
**要改进此问题吗?**更新此问题,使其仅针对editing this post的一个问题。

7年前关闭。
Improve this question
是否可以从Windows应用程序形式的网站下载文件并将其放入某个目录?

zpjtge22

zpjtge221#

关于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");

字符串

oymdgrw7

oymdgrw72#

使用WebClient.DownloadFile

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

字符串

cigdeys3

cigdeys33#

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

以下是一个包含这些选项的示例:

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

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

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

cetgtptt

cetgtptt4#

当然,你只需要使用HttpWebRequest
设置好HttpWebRequest后,您可以将响应流保存到文件StreamWriter(根据mimetype,可以是BinaryWriter,也可以是TextWriter)中,并且您的硬盘上有一个文件。
编辑:忘记了WebClient。这很好用,除非你只需要使用GET来检索你的文件。如果网站要求你向它提供POST信息,你就必须使用HttpWebRequest,所以我留下我的答案。

wnavrhmk

wnavrhmk5#

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

using System.Net;

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

字符串

ni65a41a

ni65a41a6#

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

rsl1atfo

rsl1atfo7#

试试这个例子:

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(path);
  HttpContext.Current.Response.End();
}

字符串
具体实现如下:

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


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

相关问题