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

C#生成Zip文件返回后无效,请求排查代码问题

问题排查及修复方案

你的代码生成的Zip文件损坏,主要有以下几个问题及对应的修复方式:

1. 不必要的BinaryWriter使用

你用BinaryWriter写入文件内容到Zip条目流中,这完全是多余的——虽然理论上不会直接导致Zip损坏,但会增加不必要的开销,且容易引发潜在的流操作问题。直接使用条目流的Write方法写入字节数组更可靠。

2. 错误的流位置设置时机

你在ZipArchive的using块内部设置zipStream.Position = 0,但此时ZipArchive还未完成Zip文件的收尾写入(比如中央目录结构)。当ZipArchive被释放时,会向流中追加关键的Zip结束数据,这会导致流的位置自动移到末尾。虽然MemoryStream.ToArray()会返回整个流的内容,不受当前位置影响,但这个设置属于无效操作,容易混淆逻辑。

修复后的代码

public IActionResult OnPost()
{
    Username = HttpContext.Session.GetString("Username");
    string[] FilePaths = Request.Form["FilePath"];
    Dictionary<string, byte[]> fileList = new Dictionary<string, byte[]>();
    byte[] retVal = null;

    foreach (var path in FilePaths)
    {
        string fullPath = Path.Combine(@"C:\Downloads\", Username, path);
        // 添加文件存在性检查,避免读取不存在的文件导致异常
        if (!System.IO.File.Exists(fullPath))
        {
            return BadRequest($"文件不存在:{fullPath}");
        }
        byte[] bytes = System.IO.File.ReadAllBytes(fullPath);
        fileList.Add(path, bytes);
    }

    using (MemoryStream zipStream = new MemoryStream())
    {
        using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
        {
            foreach (var file in fileList)
            {
                var demoFile = archive.CreateEntry(file.Key);
                // 直接使用条目流写入字节数组,无需BinaryWriter
                using (var entryStream = demoFile.Open())
                {
                    entryStream.Write(file.Value, 0, file.Value.Length);
                }
            }
        }
        // 此时ZipArchive已完成所有写入操作,直接获取流的全部内容
        retVal = zipStream.ToArray();
    }
    return File(retVal, MediaTypeNames.Application.Zip, "test.zip");
}

额外建议

  • 添加异常处理逻辑:捕获文件读取时的IO异常,避免因单个文件读取失败导致整个Zip生成失败
  • 检查FilePaths是否为空:如果没有选中任何文件,生成的空Zip可能会导致解压工具报错
  • 避免硬编码路径:@"C:\Downloads\"建议配置到应用设置中,增强代码灵活性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:05:18