c#

使用C#下载文件的多种方法

小亿
983
2024-01-04 06:29:20
栏目: 编程语言

在C#中,有多种方法可以下载文件。下面是其中几种常见的方法:

  1. 使用WebClient类:
string url = "http://example.com/file.txt";
string savePath = "C:\\downloads\\file.txt";

using (WebClient client = new WebClient())
{
    client.DownloadFile(url, savePath);
}
  1. 使用HttpClient类:
string url = "http://example.com/file.txt";
string savePath = "C:\\downloads\\file.txt";

using (HttpClient client = new HttpClient())
{
    using (HttpResponseMessage response = await client.GetAsync(url))
    {
        using (Stream stream = await response.Content.ReadAsStreamAsync())
        {
            using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
            {
                await stream.CopyToAsync(fileStream);
            }
        }
    }
}
  1. 使用WebRequest和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 stream = response.GetResponseStream())
{
    using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
    {
        stream.CopyTo(fileStream);
    }
}

response.Close();

请注意,以上代码示例中的URL和保存路径应根据实际情况进行更改。另外,下载文件时可能需要处理一些异常情况,例如网络连接失败或文件无法访问等。

0
看了该问题的人还看了