Home > Blockchain >  PowerShell: Error when reading files that are open in other programs
PowerShell: Error when reading files that are open in other programs

Time:04-26

Hello PowerShell Experts,

The script snippet below works when adding files to Zip file. However, if the file to be added is open in another program then it fails with exception, "The process cannot access the file[..]". I tried using [IO.FileShare]::ReadWrite but no success yet.

Any suggestion as to how to open the files for reading and writing to zip regardless whether the file is open in another program or not?

Script Source

# write entries with relative paths as names
foreach ($fname in $FullFilenames) {
    $rname = $(Resolve-Path -Path $fname -Relative) -replace '\.\\',''
    Write-Output $rname
    $zentry = $zip.CreateEntry($rname)
    $zentryWriter = New-Object -TypeName System.IO.BinaryWriter $zentry.Open()
    $zentryWriter.Write([System.IO.File]::ReadAllBytes($fname)) #FAILS HERE
    $zentryWriter.Flush()
    $zentryWriter.Close()
}

CodePudding user response:

Since we're missing some important part of your code, I'll just assume what might work in this case, and following assumptions based on your comments.

First you would open the file with FileShare.ReadWrite:

$handle = [System.IO.File]::Open($fname, 'Open', 'Read', 'ReadWrite')

Then you should be able to use the .CopyTo(Stream) method from FileStream:

$zentry  = $zip.CreateEntry($rname)
$zstream = $zentry.Open()
$handle.CopyTo($zstream)
$zstream.Flush()
$zstream.Dispose()
$handle.Dispose()
  • Related