【问题标题】:ZipArchive serves up invalid file on live serverZipArchive 在实时服务器上提供无效文件
【发布时间】:2015-12-20 11:09:42
【问题描述】:

我在处理程序中使用 ZipArchive,以便使用内存流和 Web 处理程序为用户提供服务。在我将应用程序上传到实时站点之前,这一直有效。

这是我的代码。

using (ZipArchive newArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
    newArchive.CreateEntryFromFile(fileName, Path.GetFileName(fileName));
    if (File.Exists(acRefFile))
    {
        newArchive.CreateEntryFromFile(acRefFile,
            newACRefName + Path.GetExtension(acRefFile));
    }
    else
    {
        SystemLogManager sysLogMgr = new SystemLogManager();
        sysLogMgr.AddErrorMessage(acRefFile, "File not found");
    }
    if (File.Exists(exRefFile))
    {
        newArchive.CreateEntryFromFile(exRefFile,
            newExRefName + Path.GetExtension(exRefFile));
    }
    else
    {
        SystemLogManager sysLogMgr = new SystemLogManager();
        sysLogMgr.AddErrorMessage(exRefFile, "File Not Found");
    }
    if (File.Exists(exRef2File))
    {
        newArchive.CreateEntryFromFile(exRef2File,
            newExRef2Name + Path.GetExtension(exRef2File));
    }
}
memoryStream.Position = 0;
byte[] bytes = memoryStream.GetBuffer();
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = "application/zip";
context.Response.AddHeader("content-disposition",
    string.Format("attachment; filename =app_{0}_{1}.zip", appForm.Cand_sno,
        appForm.App_year));
context.Response.BinaryWrite(bytes.ToArray());
context.Response.Flush();

下图显示了下载的 zip 文件和生成的错误。

那么代码中是否有任何错误或我可以尝试服务器端的东西?

更新 1: 根据收到的 cmets,我尝试将 zip 文件直接添加到服务器上。同样的问题发生在 zip 被“损坏”中。

更新 2: 进一步调查我现在发现使用 7zip 而非标准 Windows 解压缩时会打开 zip 文件。当右键单击提取所有消息状态时,zip 为空。

谢谢

【问题讨论】:

  • 您的开发机器和服务器是基于 Windows 的机器吗?您是否检查过服务器事件/应用程序日志?
  • 开发和服务器都是基于 Windows 的,都运行正确版本的 .net。我查看了应用程序日志并注意到这是一个可能的原因。
  • 是每次都“损坏”还是 10 次中有 9 次?
  • 是的,每次都“损坏”。
  • 你读过stackoverflow.com/questions/12347775/…stackoverflow.com/questions/17232414/… 似乎都有一个“工作”版本...值得一试。

标签: c# asp.net iis


【解决方案1】:

所以这个问题的解决方法是将byte[] bytes = MemoryStream.GetBuffer(); 更改为byte[] bytes = MemoryStream.ToArray(); 这样做只是获取使用的字节而不是缓冲区添加的额外字节。

【讨论】:

  • 这也解决了我的问题。 result.Content = new ByteArrayContent(memoryStream.ToArray());
【解决方案2】:

我使用 ZipFile 类,结果永远不会损坏。 你可以试试这个吗?

ZipFile.CreateFromDirectory("C:\somefolder", "C:\someotherfolder\somefile.zip");

【讨论】:

  • ZipFile 看起来好像直接从目录内容创建一个 zip 文件。我不想使用来自不同位置的一组指定文件创建 zip 文件。
  • 这是对的,但如果 ZipFile 工作正常,您可以创建一个方法 1) 将所有文件复制到临时目录中 2) 将目录压缩到临时 zip 文件中 3) 删除临时目录 4)返回压缩文件
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
相关资源
最近更新 更多