End of Central Directory record could not be found

user2726975 picture user2726975 · Jan 6, 2014 · Viewed 95.1k times · Source

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

Answer

crthompson picture crthompson · Jan 6, 2014

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

  1. The archive is corrupt.
  • Solution - The archive will need repairing.
  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.
  1. There is more than 1 part to the archive.
    • A multi part zip file.
    • Solution - Read in all the files before decompression.
  2. 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.