End of Central Directory record could not be found
Asked Answered
B

18

71

I am downloading a zip file using c# program and I get the error

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)

Here's the program

    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();
    }

I do not understand the error. Can anybody explain this Thanks MR

Bibcock answered 6/1, 2014 at 22:21 Comment(4)
Why did you delete your old question? you don't even include the fact that you are getting System.IO.InvalidDataExceptionBanwell
If you must open that file, I found a reference that perhaps unjarring the file would work. jar xvf corrupt.zip. obviously, this is not for your code, but i thought it worth mentioning if you needed to get the uncorrupted files out.Inclose
Could this be caused by trying to unzip a *.gz or *.7z file?Ennius
In my case WebClient.DownloadFile() produced a file around 13KB that should have been more like 8MB. So +1 on "is it corrupt". Now to go solve me download problem.Uncommunicative
I
68

The problem is ZipFile can't find the line of code that signals the end of the archive, so either:

  1. It is not a .zip archive.

    • It may be a .rar or other compressed type. Or as I suspect here, you are downloading an html file that auto-redirects to the zip file.
    • Solution - Gotta find a correct archive to use this code.
  2. The archive is corrupt.

    • Solution - The archive will need repairing.
  3. There is more than 1 part to the archive.

    • A multi part zip file.
    • Solution - Read in all the files before decompression.
  4. As @ElliotSchmelliot notes in comments, the file may be hidden or have extended characters in the name.

    • Solution - Check your file attributes/permissions and verify the file name.

Opening the file with your favorite zip/unzip utility (7-zip, winzip, etc) will tell which of these it could be.

Inclose answered 6/1, 2014 at 22:23 Comment(6)
I do not know how it is getting corrupted. There is a webpage with a download button which I automatically click in the C# program. This should download the zip files which has many other excel files. If. I do not use the c# program and go to webpage directly and click on button, there is a zip file that gets downloaded. I have used request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); I do not know how to debug this.Bibcock
You are saving your file in zipFilePath. Just go open it there and check out the file.Inclose
The assumption now is that its the server end of things that is bad. There doesnt appear to be anything wrong with your code. You could try pointing your code at another zip file and see if it can download it. I bet it does.Inclose
"Opening the file with your favorite zip utility will tell which of these it could be." - could you enhance your answer by specifying how that is going to work out, please? I am facing the same error message, and at least 7zip and Windows Explorer will open the file without complaining.Bisutun
@O.R.Mapper, if it does not complain, then the file is ok from a OS standpoint, but perhaps you are corrupting it when you bring it in. Also you might think about that a multi-part file would be opened properly in 7-zip or windows because the others were right next to it.. but might fail in code.Inclose
Ran into this error while attempting to zip/unzip a hidden file (name started with "$")Distribution
B
17

From your old question you deleted.

I get System.IO.InvalidDataException: End of Central Directory record could not be found.

This most likely means whatever file you are passing in is malformed and the Zip is failing. Since you already have the file outfile on the hard drive I would recommend trying to open that file with with windows built in zip extractor and see if it works. If it fails the problem is not with your unzipping code but with the data the server is sending to you.

Banwell answered 6/1, 2014 at 22:23 Comment(0)
S
13

I have the same problem, but in my case the problem is with the compression part and not with the decompression.

During the compression I need use the "Using" statament with the Stream and the ZipArchive objects too. The "Using" statament will Close the archive properly and I can decompress it without any problem.

The working code in my case in 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
Suppurative answered 17/7, 2016 at 15:55 Comment(0)
N
4

In my case i absolutely KNEW that my zip was not corrupted, and I was able to figure out through trial and error that I was extracting the files to a directory with the filename and extension in the FOLDER Name.

So Unzipping /tmp/data.zip to:

/tmp/staging/data.zip/files_go_here

failed with the error [End of Central Directory record could not be found]

but extracting data.zip to this worked just fine:

/tmp/staging/data/files_go_here

While it might seem unusual to some folks to name a folder a filename with extension, I can't think of a single reason why you should not be able to do this, and more importantly -- the error returned is not obviously related to the cause.

I was getting the same error with both the System.IO.Compression library and 3rd party packages such as SharpZipLib -- which is what eventually clued me in that it was a more general issue.

I hope this helps someone and saves them some time/frustration.

Notornis answered 11/11, 2020 at 19:21 Comment(1)
Azure DevOps Pipeline: This prompted me in the right direction and just went to my PublishBuildArtifact step and removed the .zip I added there earlier. Just remember to update the target Release tasks to point to the new path after running it once.Consistence
T
3

I encountered this same problem. There are many types of compression, .zip being only one of the types. Look and make sure that you aren't trying to 'unzip' a .rar or similar file.

Torso answered 23/11, 2014 at 2:25 Comment(0)
M
2

I used SharpCompress C#.net Library available via Nuget Package manager, it solved my purpose of unzipping.

Midlands answered 10/4, 2017 at 10:30 Comment(1)
I would say that System.IO gave me an error "Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory" on a file that was corrupt. With SharpCompress I was able to recover most of the archive entries. +1Folkrock
D
2

I just came across this thread when I had the same error from a PowerShell script calling the Net.WebClient DownloadFile method.

In my case, the problem was that the web server was unable to provide the requested zip file, and instead provided an HTML page with an error message in it, which obviously could not be unzipped.

So instead, I created an exception handler to extract and present the "real" error message.

Daugherty answered 19/4, 2018 at 2:38 Comment(2)
Similarly, I was trying to use a github repo reference but should have been using raw.githubusercontent.com...Emissary
Its very likely that the OP is having this same problem. The html is just redirecting to a zip file, but the code isnt a browser, so doesnt redirect.Inclose
M
2

I also had this error because I was trying to open a .json file as a .zip archive:

using(ZipArchive archive = ZipFile.Open(fileToSend.FilePath, ZipArchiveMode.Read))
{ 
    ZipArchiveEntry entry = archive.GetEntry(fileToSend.FileName);
    using (StreamReader reader = new StreamReader(entry.Open(), Encoding.UTF8))
    {
        fileContent = reader.ReadToEnd();
    }
}

I was expecting that fileToSend.FilePath = "C:\MyProject\mydata.zip"

but it was actually fileToSend.FilePath = "C:\MyProject\mydata.json" and that was causing the error.

Martlet answered 5/9, 2022 at 13:8 Comment(0)
M
1

Might be useful to someone else. I dealt with this by adding an exception to my code, which then:

  1. Creates a temporary directory
  2. Extracts the zip archive (normally works)
  3. Renames the original ziparchive to *.bak
  4. Zips and replaces the original archive file with one that works
Montenegro answered 21/3, 2018 at 9:58 Comment(0)
S
1

For me, the problem had to do with git settings.

To solve it, I added:

*.zip binary

to my .gitattributes file.

Then I downloaded an uncorrupted version of the file (without using git) and added a new commit updating the .zip file to the uncorrupted version and also updating the .gitattributes file.

I wish I could avoid adding that extra commit to update the .zip file, but the only way I can think of avoiding that would be to insert a commit updating the .gitattributes file into or before the commit that added the .zip file (using a rebase) and using git push -f to update the remote repo, but I can't do that.

Sevier answered 14/1, 2022 at 19:59 Comment(0)
M
0

Write down the stream to a file then inspect it with a (hex) editor.
I got the same message in Visual Studio when downloading nupkg from nuget.org. It was because nuget.org was blacklisted by the firewall. So instead of the pkg I got a html error page which (of course) cannot be unzipped.

Millwater answered 11/12, 2019 at 16:48 Comment(0)
C
0

In my case: I was mistakenly saving an input stream to *.zip.

While Archive Utility had no issues opening the file, all the rest failed (unzip cmd or java libs) with the same "end of central" error.

The plot-twist was: the file I'm downloading is in gzip format, i.e. *.gz, and not zip.

Cowlick answered 16/1, 2022 at 19:22 Comment(0)
K
0

Make sure it is a zip file you trying to decompress.

The web-service I querying zips results when there are two files, but in this instance it was just returning one. My code was saving the embedded base64 as a stream and therefore my code was assigning the zip extension.

Whereas it was already actually just a plain PDF...

Kyd answered 17/1, 2022 at 14:0 Comment(0)
T
0

In my case, I was receiving this error in a combination with FileSystemWatcher, which triggered a processing method upon the zip archive before the archive was fully copied/created in its target folder.

I solved it with a check of whether the zip archive was truly eligible for reading in a try/catch block within a while loop.

Trinhtrini answered 3/2, 2022 at 10:44 Comment(0)
O
0

My solution compress with powershell

Compress-Archive * -DestinationPath a.zip
Oklahoma answered 8/4, 2022 at 0:47 Comment(0)
R
0

https://github.com/dotnet/runtime/pull/67332

There are many reasons for this problem, but in addition to the reasons listed in other answers, the most likely reason is that the underlying implementation of .net is not of high quality. It lacks support for some legal directory path symbols. For example paths with dots. Although it seems that the issue is officially partially resolved, so far I don't know if this commit completely solves the problem, and in which version the update will eventually be released. I personally currently use .net 6.0 desktop runtime, and this bug still exists.

But another possible problem is that maybe your path itself looks fine. But there are actually some problems. For example: somepath="\"\"" In this case, it is obvious that the path contains repeated double quotes. However, when debugging, you may accidentally overlook this problem.

Religious answered 8/8, 2023 at 2:16 Comment(0)
F
0

The exception related to the stack trace is: (as also specified in this answer)

System.IO.InvalidDataException: End of Central Directory record could not be found.

In my case, the exception was thrown by the ZipArchive constructor when providing it with an input stream for an empty zip file.

I could verify that the zip file was empty by manually trying to extract its contents in the file explorer. The manual extraction was unsuccessful and provided a warning telling me that the zip file needed content before extraction.

Fauver answered 20/2 at 8:25 Comment(0)
P
-2

I found resolution.

Move "Tools->Nuget PackageManager ->Package Manager Settings" and in "Nuget Package Manager" -General Tab , click Clear All Nuget Caches button and OK. You can install package from online

Pokpoke answered 12/10, 2020 at 23:23 Comment(1)
Could you explain how your answer makes a runtime error disappear? The question isn't how to install a package.Brancusi

© 2022 - 2024 — McMap. All rights reserved.