Powershell - 从.zip存档读取文件失败

时间:2016-03-07 12:04:01

标签: powershell

我目前正在尝试读取.zip存档中特定.xml文件的内容而不将其解压缩。
代码很简单,但不知何故有几个字节进入缓冲区,因此无法使用文件内容。

这是相应的代码:

    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
    $arch = [System.IO.Compression.ZipFile]::OpenRead("C:\file.zip")

    $entr = $arch.Entries | ?{$_.Name -like "test.xml"}
    if(!$entr)
    {throw [System.Exception] "Could not find the .xml file"}

    $buf = New-Object System.Byte[]($entr.Length)
    $entr.Open().Read($buf, 0, $entr.Length) | Out-Null

    $xml = [xml] ([System.Text.Encoding]::Unicode.GetString($buf))

代码非常直截了当我说,但遗憾的是$buf的前两个字节似乎总是等于255254,这会导致Powershell' s xml解析器抛出异常 作为临时解决方法,我尝试省略前两个字节,但这只会导致最后两个字节出现同样的问题。

这引出了我的问题,缓冲区怎么可能搞砸了呢? 这样做是错误的吗?我错过了什么?

非常感谢任何帮助!

更新

好吧,似乎Windows使用UTF-16作为内部编码,这意味着前两个字节是Byte Order Mark (BOM)。我希望GetString()方法能够识别BOM,有人可以澄清这个吗?

1 个答案:

答案 0 :(得分:0)

您需要将您的Stream封装到StreamReader然后使用ReadToEnd()方法,我希望能够尊重BOM:

$reader = new-object System.IO.StreamReader($entr.Open())
$contents = $reader.ReadToEnd()
$reader.Close()
相关问题