新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C#实现HTTP下载文件的有哪些方法

发布时间:2024-03-18 20:39:35

C#实现HTTP下载文件的有哪些方法

在C#中实现HTTP下载文件的方法是使用HttpClient类发送HTTP要求并下载文件。以下是一个简单的示例代码:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://example.com/file.jpg";
        string savePath = "C:\path\to\save\file.jpg";

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

            if (response.IsSuccessStatusCode)
            {
                using (var fileStream = System.IO.File.Create(savePath))
                {
                    await response.Content.CopyToAsync(fileStream);
                }

                Console.WriteLine("File downloaded successfully.");
            }
            else
            {
                Console.WriteLine($"Failed to download file. Status code: {response.StatusCode}");
            }
        }
    }
}

在上面的示例中,我们首先创建一个HttpClient实例,然后发送一个GET要求以下载文件。如果要求成功,就将响应内容写入到本地文件中。最后,我们输出下载结果。