PowerShell:读取在其他程序中打开的文件时的错误

发布于 2025-01-23 19:28:30 字数 815 浏览 2 评论 0原文

Hello PowerShell专家,

将文件添加到zip文件时,下面的脚本片段可工作。但是,如果要添加的文件是在另一个程序中打开的,则它将失败,而“该过程无法访问文件[..]”。我尝试使用[io.fileshare] :: rearwrite,但还没有成功。

关于如何在另一个程序中打开文件,如何打开如何打开读取和写作的文件对zip进行读取和写作的建议?

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()
}

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()
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独自←快乐 2025-01-30 19:28:30

由于我们错过了您的代码中一些重要的部分,因此我只是假设在这种情况下可能有效的内容,并根据您的评论遵循假设。

首先,您将使用 <<代码> fileshare.readwrite

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

然后您应该能够使用 /a>:

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

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文