Search code examples
c#.netsystem.io.packaging

Opening a System.IO.Packaging.Package from a non-seekable Stream


I am trying to unpack a System.IO.Packaging.Package that I received from a web server. That is, I am using the System.IO.Packaging.Package.Open(Stream) method and passing it the response stream of a System.Net.HttpWebResponse. Unfortunately, this raises a System.ArgumentException telling me that it

Cannot operate on [a] stream that does not support seeking.

Looking at the reference source it turns out that System.IO.Packaging.Package uses System.IO.Packaging.ZipPackage as its only implementation which in turn uses the internal ZipArchive class. And sure enough, the ValidateModeAccessStreamStreamingCombinations() method raises this exception in line 588 if stream.CanSeek is false which is the case for the response stream from my HttpWebResponse.

However, there is a magic streaming parameter which, apparently, is always false and gets passed around from the Package.Open() method all the way down to ValidateModeAccessStreamStreamingCombinations().

So here's my question: Is there any way to use Package.Open(Stream) to construct a Package on the fly from a non-seekable stream? Or do I have to cache the stream contents somewhere, for example in a MemoryStream? (I really don't want to do that because I'm not interested in the package stream once I have unpacked it.)


Solution

  • Huh, nevermind. The streaming parameter is only intended to write a System.IO.Packaging.Package on the fly. Starting from line 954 there are a bunch of "Write-time streaimg API" methods. There also is a ThrowIfInStreamingCreation() method, which only raises an exception when I try to write a package.

    So yeah, I have to cache the non-seekable stream from the HttpWebResponse in a MemoryStream or a temporary file. No on-the-fly unpacking for me :(