ZipArchive在实际服务器上提供无效文件

3

我正在使用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文件和生成的错误。 Zip error 所以代码中是否有任何问题或者我可以尝试一些服务器端的操作?
更新1: 根据收到的评论,我尝试直接将zip文件添加到服务器上。出现与zip“损坏”相同的问题。
更新2: 进一步调查后,我现在发现使用7zip时可以打开zip文件,但是使用标准的Windows解压缩时无法打开。当右键提取全部时,消息显示zip为空。
谢谢

你的开发机和服务器是否为基于 Windows 的机器?并且你有检查过服务器事件/应用程序日志吗? - Paul Zahra
每次都是“损坏”的吗?还是十次里面有九次是“损坏”的? - Paul Zahra
每次都会出现“损坏”的问题。 - Dashwall
嗨,保罗。我已经阅读了两个问题,唯一的真正区别是在使用文件流提供文件之前将其存储在本地。我也会尝试处理流。 - Dashwall
尝试简化问题。不要进行文件传输,而是将其保存在文件系统中并尝试打开它。它是否已损坏? - Emanuele Greco
显示剩余5条评论
2个回答

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

这也解决了我的问题。result.Content = new ByteArrayContent(memoryStream.ToArray()); - Dragos Durlut

0

我使用ZipFile类,结果从未损坏。 你可以试试吗?

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

ZipFile看起来像是直接从目录内容创建zip文件。我想要使用从不同位置指定的一组特定文件创建zip文件。 - Dashwall
这是正确的,但如果ZipFile正常工作,您可以创建一个方法:1)将所有文件复制到临时目录2)将目录压缩为临时zip文件3)删除临时目录4)返回zip文件。 - Emanuele Greco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接