0

The following code block is falling into the catch, and the zip file does NOT exist already, I check for that in the code block prior to this code block.

 try
 {
     ZipFile.CreateFromDirectory(pathToFilesToZip, zipPath, CompressionLevel.Fastest, true);
     //ZipFile.ExtractToDirectory(zipPath, pathToStoreNewZipFile);
     return true;
  }
  catch (Exception ex)
  {
      //log error here
      var errorMessage = ex.InnerException;
      Console.WriteLine(errorMessage);
      return false;
  }

The issue is the code worked, the zip file was created in its proper location. Even stranger, ex is null in the catch block. Why is an executed code line generating an exception?

dinotom
  • 4,990
  • 16
  • 71
  • 139
  • I had this problem before and I removed the code in the exception portion had random issues so I wrapped the code around a using and eliminated the try catch I think it might be a bug you can try the same thing.. – MethodMan Sep 21 '16 at 20:10
  • @MethodMan...Using what? what within this code is disposable? – dinotom Sep 21 '16 at 21:59
  • @dinotom Is it possible that the zip file already exists, perhaps from the first execution? – sly Sep 21 '16 at 22:17
  • The zip does not exist prior to the code running, I already check for that – dinotom Sep 21 '16 at 22:22
  • An InnerException can have its own InnerException and so on. I guess if you know exactly what exception stack you are looking for then you could go straight to the InnerException, but otherwise there may be 10 exceptions chained together through InnerException's and you'd only grab the first one. I use [this method](http://stackoverflow.com/a/9314420/5095502) as a simple way to get to all the inner exceptions, `while (ex != null) {print ex.message; ex = ex.InnerException;}` – Quantic Sep 21 '16 at 22:38
  • @Quantic...I fully drilled down, there is absolutely nothing in the exception. methodman has to be right, this is a bug in ZipFile dll – dinotom Sep 22 '16 at 00:58
  • @dinotom Right, I was just commenting against your comment: "Even stranger, ex is null in the catch block" (I assume you meant `ex.InnerException` is null). Just pointing out that `var errorMessage = ex.InnerException;` is improper unless you know exactly that the exception even has an inner exception (often it's `null` as you saw), and that you only want the first InnerException and not any of the other ones. – Quantic Sep 22 '16 at 15:32
  • No problem, and I did mean ex is null, because it is null here – dinotom Sep 22 '16 at 15:49

1 Answers1

2

An exception is thrown if the zip file to be created already exists. Try deleting the zip file first by adding the following line prior to creating the zip file:

File.Delete(zipPath);

With respect to the null exception, instead of logging ex.InnerException just log ex or ex.Message. The message in the exception that I'm seeing is:

The file 'C:\Temp\temp.zip' already exists.

sly
  • 300
  • 1
  • 5