question

HemanthB-9452 avatar image
0 Votes"
HemanthB-9452 asked HemanthB-9452 commented

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

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


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Castorix31 avatar image
0 Votes"
Castorix31 answered HemanthB-9452 commented

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);
                     }
                 }
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks so much @Castorix31! It worked

0 Votes 0 ·