Powershell - Reading file from .zip archive fails
<p>I'm currently trying to read the contents of a specific .xml file in a .zip archive without extracting it.<br>
The code is simple, but somehow a couple of bytes slip into the buffer, making it impossible to use the contents of the file.</p>

<p>This is the respective code:</p>

<pre><code>    [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))
</code></pre>

<p>The code is pretty straightforward I'd say, but sadly the first two bytes of <code>$buf</code> seem always equal to <code>255</code> and <code>254</code>, which causes Powershell's xml parser to throw an exception.<br>
As a temporary workaround I tried omitting the first two bytes, but that simply caused the same problem to occur with the last two bytes.</p>

<p>That leads me to my question, how is it possible that the buffer is messed up?<br>
Is my way of doing this wrong? What did I miss?</p>

<p>Any help is higly appreciated!</p>

<p><strong>UPDATE:</strong></p>

<p>Well, it seems as Windows uses UTF-16 as internal encoding, which would mean that the two first bytes are the <code>Byte Order Mark (BOM)</code>. I would expect the <code>GetString()</code> method to recognize the <code>BOM</code>, could someone clarify on this?</p>