Search code examples
wcfstreamdotnetzip

How can I get Seek method on Stream in WCF streaming mode?


Let's say I have a WCF method

[OperationContract]
bool UploadFile(Stream stream);

How can I get Seek functionality on stream?

I need it for two requirements:

  1. Reading first four bytes of the stream to determine if the file type has 50 4B 03 04 ZIP file signature, and rewinding (stream.Seek(0, SeekOrigin.Begin))
  2. Reading a DotNetZip Ionic.Zip.ZipFile from Stream: ZipFile zip = ZipFile.Read(stream) (needs the stream to be seekable)

Solution

  • As CodeCaster mentioned, you can't seek a WCF stream. You'll have to solve your problems using a different approach:

    1. To peek at the streams' header, I'd read the first four bytes of the stream, then use something like ConcatenatedStream to concatenate the first four bytes that you can put into a MemoryStream and the rest of the original WCF stream. This will basically buffer part of the stream, yet the concatenated stream still presents a stream that is at position 0 without requiring a seek.

    2. If DotNetZip needs the ability to seek then it needs the ability to access any part of the file. You'll need to read the entire WCF stream into a MemoryStream and provide it to DotNetZip. A more efficient alternative would be to write your own Stream wrapper class that will buffer only as far as the highest stream position that has been requested, so that if DotNetZip only seeks around in the first megabyte of the file, you'll only buffer a megabyte of data (and not the whole 50 GB file).