在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)

方法1:使用 HttpClient(异步,推荐)

csharp

复制代码
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

class FileDownloader
{
    public static async Task DownloadFileAsync(string url, string localFilePath)
    {
        using (HttpClient httpClient = new HttpClient())
        {
            try
            {
                // 发送GET请求
                HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                response.EnsureSuccessStatusCode(); // 确保响应成功

                // 创建文件流
                using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    // 将网络流复制到文件流
                    await response.Content.CopyToAsync(fileStream);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"下载失败: {ex.Message}");
                throw;
            }
        }
    }
}

// 使用示例
await FileDownloader.DownloadFileAsync(
    "https://example.com/files/document.pdf",
    @"C:\Downloads\document.pdf"
);

方法2:使用 WebClient(同步/异步,旧版方法)

csharp

复制代码
using System.Net;

// 异步版本
public static async Task DownloadWithWebClientAsync(string url, string savePath)
{
    using (WebClient client = new WebClient())
    {
        await client.DownloadFileTaskAsync(new Uri(url), savePath);
    }
}

// 同步版本(不推荐,会阻塞线程)
public static void DownloadWithWebClient(string url, string savePath)
{
    using (WebClient client = new WebClient())
    {
        client.DownloadFile(url, savePath);
    }
}

方法3:高级 HttpClient(支持进度报告)

csharp

复制代码
public static async Task DownloadWithProgressAsync(string url, string savePath, IProgress<float> progress = null)
{
    using (HttpClient httpClient = new HttpClient())
    {
        HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
        response.EnsureSuccessStatusCode();

        using (Stream contentStream = await response.Content.ReadAsStreamAsync())
        using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
        {
            var totalBytes = response.Content.Headers.ContentLength.GetValueOrDefault();
            var buffer = new byte[8192];
            long bytesRead = 0;
            int bytesReceived;

            while ((bytesReceived = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
            {
                await fileStream.WriteAsync(buffer, 0, bytesReceived);
                bytesRead += bytesReceived;
                
                // 报告进度(如果有)
                progress?.Report((float)bytesRead / totalBytes);
            }
        }
    }
}

// 使用带进度条的示例
var progress = new Progress<float>(p => Console.WriteLine($"下载进度: {p:P}"));
await DownloadWithProgressAsync(
    "https://example.com/largefile.zip",
    @"C:\Downloads\largefile.zip",
    progress
);

注意事项:

  1. 异常处理:务必添加 try-catch 处理网络异常、文件权限问题等

  2. 路径安全:检查本地路径是否合法,目录是否存在

    csharp

    复制代码
    var directory = Path.GetDirectoryName(savePath);
    if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
  3. 文件名提取:从URL自动获取文件名

    csharp

    复制代码
    string GetFileNameFromUrl(string url)
    {
        Uri uri = new Uri(url);
        return Path.GetFileName(uri.LocalPath);
    }
  4. 超时设置

    csharp

    复制代码
    httpClient.Timeout = TimeSpan.FromMinutes(30); // 设置超时时间
  5. 取消支持:可添加 CancellationToken 支持取消操作

推荐方案:

  • 现代应用使用 HttpClient + 异步流复制(方法1或方法3)

  • 需要进度报告时使用带缓冲读取的方法3

  • 简单脚本可使用 WebClient 简化代码

  • 始终使用异步方法避免阻塞UI线程

根据实际需求选择合适的方法,并添加必要的错误处理和资源清理逻辑。

相关推荐
南境十里·墨染春水1 分钟前
C++ 笔记 thread
java·开发语言·c++·笔记·学习
南境十里·墨染春水2 分钟前
C++ 笔记 高级线程同步原语与线程池实现
java·开发语言·c++·笔记·学习
来自远方的老作者1 小时前
第10章 面向对象-10.4 继承
开发语言·python·继承·单继承·多继承·super函数
逻辑驱动的ken1 小时前
Java高频面试考点场景题09
java·开发语言·数据库·算法·oracle·哈希算法·散列表
小手cool1 小时前
如何在Java中根据另一个配对集合对一个集合进行排序
java·开发语言
升鲜宝供应链及收银系统源代码服务1 小时前
OMS 订单模块重构正式文档(一)---升鲜宝生鲜配送供应链管理系统
java·开发语言·重构·生鲜配送源代码·生鲜供应链源代码
qq_12084093712 小时前
Three.js 工程向:GLTFLoader 管线、Draco/KTX2 与资源管理
开发语言·javascript·ecmascript
下地种菜小叶2 小时前
定时任务系统怎么设计?一次讲清任务注册、分布式调度、幂等执行与失败补偿
java·开发语言·数据库·oracle·rabbitmq
csbysj20202 小时前
业务代表模式
开发语言
sghuter3 小时前
AI重塑工程师:未来核心能力全景图
开发语言·perl·composer·symfony