1

I am using Ionic zip in my WCF service to unzip files uploaded by a 'client'.The files are zipped using Ionic zip.However,there have been instances where the zipped files were 'corrupted'.Since my code scans the entire folder to look for zipped files,exceptions were thrown as it was picking up the same 'corrupted' zipped files everytime.This stopped all the other files from being processed.Here's the code:

foreach (string filePath in Directory.GetFiles(ZippedFilesDestinationFolder))
{
    using (ZipFile zip1 = ZipFile.Read(filePath))
            {
                foreach (ZipEntry e in zip1)
                {
                    e.Extract(unpackdirectory, ExtractExistingFileAction.OverwriteSilently);
                }
            }
}

I want to move the corrupted file to another folder and continue extracting the other zipped files in the folder.How should the code be modified to achieve this?

user1550951
  • 369
  • 2
  • 9
  • 26

1 Answers1

4

It stopped all other files because the exception was unhandled within the loop, causing the loop to exit. Adding a Try/Catch around the Read of Zipped files will allow files to fail but still allow next file to be processed.

foreach (string filePath in Directory.GetFiles(ZippedFilesDestinationFolder))
{
    try
    {
        using (ZipFile zip1 = ZipFile.Read(filePath))
        {
            foreach (ZipEntry e in zip1)
            {
                e.Extract(unpackdirectory, ExtractExistingFileAction.OverwriteSilently);
            }
        }
    }
    catch(Exception ex) 
    { 
        /* Log ex here */ 
        /* Move corrupt file */
    }
}
bland
  • 1,968
  • 1
  • 15
  • 22
  • Tried with a try/catch block.Still the same error.There's definitely something very obvious I am missing. – user1550951 Sep 24 '13 at 18:00
  • 2
    @user1550951 Yes, the error will still happen, but now you are catching it in the exception so you can move the file in the catch block instead and it can continue with the next loop iteration instead of stopping entirely. You likely have "break on thrown" set so exceptions inside try-catch blocks still break the debugger and that is why you still see the error. That or you are getting a error not related to unzipping (like the file is in use) so the Move fails too, you need to [update your post](http://stackoverflow.com/posts/18988534/edit) and tell us exactly what the exception says. – Scott Chamberlain Sep 24 '13 at 18:02
  • @ScottChamberlain: The 'obvious' thing was moving the corrupted file to another location in the catch block.I was logging the error,throwing a user-friendly error message to the user but not moving the file to another folder. – user1550951 Sep 24 '13 at 18:14