无法找到中央目录结束记录
我正在使用c#程序下载一个zip文件,我收到错误
at System.IO.Compression.ZipArchive.ReadEndOfCentralDirectory() at System.IO.Compression.ZipArchive.Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen) at System.IO.Compression.ZipArchive..ctor(Stream stream, ZipArchiveMode mode, Boolean leaveOpen, Encoding entryNameEncoding) at System.IO.Compression.ZipFile.Open(String archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding) at System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileN ame, String destinationDirectoryName, Encoding entryNameEncoding) at System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileN ame, String destinationDirectoryName)
这是程序
response = (HttpWebResponse)request.GetResponse(); Stream ReceiveStream = response.GetResponseStream(); byte[] buffer = new byte[1024]; FileStream outFile = new FileStream(zipFilePath, FileMode.Create); int bytesRead; while ((bytesRead = ReceiveStream.Read(buffer, 0, buffer.Length)) != 0) outFile.Write(buffer, 0, bytesRead); outFile.Close(); response.Close(); try { ZipFile.ExtractToDirectory(zipFilePath, destnDirectoryName); } catch (Exception e) { Console.WriteLine(e.ToString()); Console.ReadLine(); }
我不明白这个错误。 任何人都可以解释这个谢谢MR
问题是Unzip无法找到表示存档结束的代码行,因此:
- 存档已损坏。
- 它不是.zip存档。 (它可能是.rar或其他压缩类型)
- 存档有1个以上的部分。 (多部分拉链)
使用您喜欢的zip实用程序打开文件将告诉它可能是哪一个。
从您删除的旧问题。
我收到System.IO.InvalidDataException:找不到中央目录记录的结尾。
这很可能意味着您传入的文件格式不正确且Zip失败。 由于您已经在硬盘驱动器上安装了文件outfile
,我建议尝试使用带有zip解压缩器的windows打开该文件,看看它是否有效。 如果失败,问题不在于您的解压缩代码,而在于服务器发送给您的数据。
我有同样的问题,但在我的情况下问题是压缩部分而不是解压缩。
在压缩过程中,我需要使用Stream和ZipArchive对象的“Using”statament。 “使用”statament将正确关闭存档,我可以毫无问题地解压缩它。
我在VB.Net中的工作代码:
Using zipSteramToCreate As New MemoryStream() Using archive As New ZipArchive(zipSteramToCreate, ZipArchiveMode.Create) ' Add entry... End Using ' Return the zip byte array for example: Return zipSteramToCreate.ToArray End Using
我遇到了同样的问题。 有许多类型的压缩,.zip只是其中一种类型。 查看并确保您没有尝试“解压缩”.rar或类似文件。
当我从调用Net.WebClient DownloadFile方法的PowerShell脚本遇到同样的错误时,我刚遇到这个post。
在我的情况下,问题是Web服务器无法提供所请求的zip文件,而是提供了一个HTML页面,其中包含错误消息,显然无法解压缩。
因此,我创建了一个exception处理程序来提取并显示“真实”错误消息。
可能对其他人有用。 我通过在代码中添加一个exception处理了这个问题,然后:
- 创建一个临时目录
- 提取zip存档(通常有效)
- 将原始ziparchive重命名为* .bak
- 使用可用的存档文件来压缩并替换原始存档文件
我使用了通过Nuget包管理器提供的SharpCompress C#.net库,它解决了我解压缩的目的。