1

disclaimer This question isn't about the appliction of Dispose(). It's not about files being inaccessible. I'm about closing the archive in the proper way without relying on disposing the object.

The following works.

ZipFile.ExtractToDirectory(file, path, true);
File.Delete(file);

This fails with exception: The process cannot access the file 'c:\temp...\file.zip' because it is being used by another process.

ZipFile.ExtractToDirectory(file, path, true);
ZipArchive archive = ZipFile.OpenRead(file);
File.Delete(file);

I've resolved it by disposing the object.

ZipFile.ExtractToDirectory(file, path, true);
ZipArchive archive = ZipFile.OpenRead(file);
archive.Dispose();
File.Delete(file);

I am worried that disposing the object is not the correct approach. Somehow I feel there should be a way to close the file before deletion. There is no such method, however. I googled it but the results I got were about memory streams, general access being denied, manual setting of the attributes.

danilo
  • 55
  • 7
  • `ZipArchive` is an `IDisposable`, so it should go in a `using` which will call `Dispose` for you automatically. `using (ZipArchive archive = ZipFile.OpenRead(file)) { // do stuff }` – Charlieface May 24 '23 at 14:30
  • 2
    Disposing is the correct thing to do. Closing an object generally just disposes it anyway. Sometimes it does something extra but often it doesn't. For instance, the `MemoryStream` class you mention inherits its `Close` method from the `Stream` class and, if you read the documentation for that method, it tells you that you can simply dispose the stream. – jmcilhinney May 24 '23 at 14:37

1 Answers1

1

The ZipFile and ZipArchive implement IDisposable, which means that it'll invoke a call to Dispose() automagically at the end of the scope. Try using block as below.

void SomeMethod(string file)
{
  using ZipArchive archive = ZipFile.OpenRead(file);
  ...
}
Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
Mittal Patel
  • 2,732
  • 14
  • 23