c#

c#下载文件的方法有哪些

小亿
289
2024-01-12 01:26:06
栏目: 编程语言

在C#中下载文件有多种方法:

  1. 使用WebClient类:可以使用WebClient类的DownloadFile方法来下载文件。以下是一个示例:
string url = "http://example.com/file.txt";
string savePath = "C:\\Downloads\\file.txt";

using (WebClient client = new WebClient())
{
    client.DownloadFile(url, savePath);
}
  1. 使用HttpClient类:可以使用HttpClient类的GetAsync方法来下载文件。以下是一个示例:
string url = "http://example.com/file.txt";
string savePath = "C:\\Downloads\\file.txt";

using (HttpClient client = new HttpClient())
{
    HttpResponseMessage response = await client.GetAsync(url);
    response.EnsureSuccessStatusCode();

    using (Stream contentStream = await response.Content.ReadAsStreamAsync(),
                  stream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
    {
        await contentStream.CopyToAsync(stream);
    }
}
  1. 使用WebRequest和WebResponse类:可以使用WebRequest类发送HTTP请求,并使用WebResponse类获取响应数据。以下是一个示例:
string url = "http://example.com/file.txt";
string savePath = "C:\\Downloads\\file.txt";

WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();

using (Stream responseStream = response.GetResponseStream(),
              stream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
{
    byte[] buffer = new byte[8192];
    int bytesRead;
    while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        stream.Write(buffer, 0, bytesRead);
    }
}

以上是三种常用的下载文件的方法,你可以根据自己的需求选择适合的方法。

0
看了该问题的人还看了