You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#实现从自动触发下载的链接下载.xlsx文件

C# 从自动触发下载的链接下载.xlsx文件

方法1:使用HttpClient(推荐,适用于.NET Core/.NET 5+)

HttpClient是官方推荐的现代HTTP客户端,支持异步操作,灵活性更强。浏览器能自动触发下载的链接,本质是服务器返回了带文件内容的响应,直接发送GET请求并将响应流写入本地文件即可,还可以从响应头提取服务器指定的文件名。

代码示例:

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

class Program
{
    static async Task Main(string[] args)
    {
        string downloadUrl = "https://xxxxx/run?app=prc/prcStart.jsp&cmd=show&project_id=PRCPROJECT102151491224824986";
        string saveDir = @"C:\Downloads";
        string savePath = Path.Combine(saveDir, "temp.xlsx");

        using (HttpClient client = new HttpClient())
        {
            // 若链接需要登录会话,可配置Cookie容器保存登录状态
            // var handler = new HttpClientHandler { CookieContainer = new CookieContainer() };
            // using (HttpClient client = new HttpClient(handler))

            using (HttpResponseMessage response = await client.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead))
            {
                response.EnsureSuccessStatusCode(); // 验证请求是否成功

                // 可选:从Content-Disposition头提取服务器指定的文件名
                if (response.Content.Headers.TryGetValues("Content-Disposition", out var values))
                {
                    string disposition = values.FirstOrDefault();
                    if (!string.IsNullOrEmpty(disposition))
                    {
                        var fileNameMatch = System.Text.RegularExpressions.Regex.Match(disposition, @"filename=""?([^""]+)""?");
                        if (fileNameMatch.Success)
                        {
                            savePath = Path.Combine(saveDir, fileNameMatch.Groups[1].Value);
                        }
                    }
                }

                // 将响应流写入本地文件
                using (Stream contentStream = await response.Content.ReadAsStreamAsync())
                using (Stream fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    await contentStream.CopyToAsync(fileStream);
                }

                Console.WriteLine($"文件已保存至:{savePath}");
            }
        }
    }
}

方法2:使用WebClient(适用于.NET Framework或简单场景)

WebClient是更简洁的旧版API,代码量少,适合快速实现基础下载需求:

代码示例:

using System;
using System.Net;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string downloadUrl = "https://xxxxx/run?app=prc/prcStart.jsp&cmd=show&project_id=PRCPROJECT102151491224824986";
        string saveDir = @"C:\Downloads";
        string savePath = Path.Combine(saveDir, "output.xlsx");

        using (WebClient client = new WebClient())
        {
            // 若需要携带登录Cookie,可设置CookieContainer
            // client.CookieContainer = new CookieContainer();

            client.DownloadFile(downloadUrl, savePath);
            Console.WriteLine($"文件已保存至:{savePath}");
        }
    }
}

关键注意事项

  • 会话保持:如果目标链接需要登录权限(比如浏览器中需登录才能下载),要先通过模拟登录请求获取Cookie,再将Cookie绑定到客户端的CookieContainer中,确保下载请求携带有效会话。
  • 异常处理:实际开发中建议添加try-catch块,处理网络连接失败、文件读写权限不足、HTTP错误码等异常场景。
  • 异步选择:HttpClient示例采用异步操作,适合UI程序避免界面阻塞;WebClient也提供DownloadFileTaskAsync异步方法,可按需选用。

内容的提问来源于stack exchange,提问作者Moritz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:04:07