Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Powershell, how do I close the handle after a ZipFile.OpenRead?

I'm making a Powershell (Version 3.0, .Net framework 4.5) script that updates some files. However, some of them need to be inspected first.

I open a JAR file and get an entry's content with the following code:

[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
$zentry = [IO.Compression.ZipFile]::OpenRead($moduleJarPath).Entries | Where-Object {$_.FullName -match '.*pom.xml'}

The entry is read using a System.IO.StreamReader, that is closed right after the read, in a finally block.

Further down the script, I'm going to update the JAR file with a newer one, that might have the same name. In that case, the script fails with:

Copy-Item : The process cannot access the file 'E:\path\to\my\artifact.jar' because it is being used by another process.

It looks like the lock is held by my own script, which seems logical since I just accessed the JAR. I'd like to close the handle so that my script can overwrite the JAR.

In the IO.Compression.ZipFile documentation, there are no "close" method.

How can I release the lock?

Thanks! :)

like image 851
Sébastien Avatar asked May 09 '14 14:05

Sébastien


1 Answers

ZipArchive, which is returned by ZipFile.OpenRead(), implements IDisposable so you would call Dispose() e.g.

$zipFile = [IO.Compression.ZipFile]::OpenRead($moduleJarPath)
$zentry = $zipFile.Entries | Where-Object {$_.FullName -match '.*pom.xml'}
...
$zipFile.Dispose()
like image 200
Keith Hill Avatar answered Nov 09 '22 20:11

Keith Hill