System.IO.InvalidDataException: 'End of Central Directory record could not be found.' while reading a zip file!

Hemanth B 886 Reputation points
2021-06-11T11:37:31.747+00:00

Hi I also created an zip file extractor in c# which would read, display and extract the selected zip file. Below is the code for reading and displaying the contents of the zip file in a listbox. Now I want to display an error message box if the zip file is corrupt or not readable or extractable. Because if there is no error message displayed, the application just crashes and displays this message: System.IO.InvalidDataException: 'End of Central Directory record could not be found.' while reading zip file

Code for reading and displaying non-corrupt zip files:

 openFileDialog1.Filter = "ZIP Folders (.ZIP)|*.zip";

            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                ZipArchive zip = ZipFile.OpenRead(openFileDialog1.FileName);
                listBox1.Items.Clear();
                foreach (ZipArchiveEntry entry in zip.Entries)
                {
                    listBox1.Items.Add(entry.FullName);
                }

            }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,419 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 88,541 Reputation points
    2021-06-11T12:03:06.767+00:00

    You can use try/catch

    Like :

                    System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
                    openFileDialog1.Filter = "ZIP Folders (.ZIP)|*.zip";
                    DialogResult result = openFileDialog1.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        ZipArchive zip;
                        try
                        {
                            zip = ZipFile.OpenRead(openFileDialog1.FileName);
                        }
                        catch (Exception ex)
                        {
                            System.Windows.Forms.MessageBox.Show("Error : " + ex.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        listBox1.Items.Clear();
                        foreach (ZipArchiveEntry entry in zip.Entries)
                        {
                            listBox1.Items.Add(entry.FullName);
                        }
                    }
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.