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

使用WebClient下载文件遇404错误求助,需保留返回文件名

解决WebClient下载返回404且获取响应文件名的问题

这问题我之前踩过一模一样的坑!浏览器能正常下载但WebClient报404,核心原因基本是WebClient默认的请求头和浏览器差异太大,被服务器拦截了,另外你还需要从响应头里提取服务器返回的文件名,不用硬编码。咱们一步步来搞定:

1. 模拟浏览器请求头(关键!)

很多服务器会校验请求的User-Agent字段,非浏览器的请求直接返回404。所以咱们给WebClient加上和浏览器一样的User-Agent,就能绕过这个限制。

2. 从响应头提取文件名

服务器返回文件时,通常会在Content-Disposition响应头里带上文件名,咱们可以解析这个头来获取真实的文件名,不用固定写死test.xlsx。

完整可运行代码

string fileUri = "https://xxxxx.xxx/ff?fid=123.456";
// 构建下载目录路径,避免硬编码拼接
string downloadDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "download");
// 确保目录存在,防止保存时报错
Directory.CreateDirectory(downloadDir);

try
{
    using (var wc = new WebClient())
    {
        // 添加浏览器的User-Agent,伪装成浏览器请求
        wc.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
        
        // 先打开响应流,同时获取响应头信息
        using (var responseStream = wc.OpenRead(fileUri))
        {
            // 解析Content-Disposition头获取文件名
            string contentDisposition = wc.ResponseHeaders[HttpResponseHeader.ContentDisposition];
            string targetFileName = "test.xlsx"; // 默认文件名
            
            if (!string.IsNullOrEmpty(contentDisposition))
            {
                // 用正则匹配filename字段,兼容带引号和不带引号的格式
                var fileNameMatch = System.Text.RegularExpressions.Regex.Match(
                    contentDisposition, 
                    @"filename=""?(?<name>[^"";]+)""?", 
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase
                );
                
                if (fileNameMatch.Success)
                {
                    targetFileName = fileNameMatch.Groups["name"].Value;
                }
            }
            
            // 拼接最终保存路径
            string savePath = Path.Combine(downloadDir, targetFileName);
            
            // 将响应流写入本地文件
            using (var fileStream = new FileStream(savePath, FileMode.Create, FileAccess.Write))
            {
                responseStream.CopyTo(fileStream);
            }
            
            Console.WriteLine($"文件下载成功,保存路径:{savePath}");
        }
    }
}
catch (Exception ex)
{
    Console.WriteLine($"下载出错:{ex.Message}");
    // log.Error($"下载失败:{ex.Message}", ex);
}

额外注意事项

  • 如果还是报404,检查浏览器的请求是否带了Cookie:打开浏览器开发者工具(F12),找到该请求的Cookie,然后添加到WebClient的Headers里:wc.Headers.Add(HttpRequestHeader.Cookie, "这里填浏览器里复制的Cookie内容");
  • 确保你的程序有下载目录的写入权限,避免保存时出现权限错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:17:48