3

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)
ipavlic
  • 4,906
  • 10
  • 40
  • 77

3 Answers3

2

I find various sources claiming you can't seek a stream in WCF.

This is supposed to be so, because in the end your data will be sent over a network socket, which by design does not support seeking (it just sends byte arrays).

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
2

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).

Community
  • 1
  • 1
Allon Guralnek
  • 15,813
  • 6
  • 60
  • 93
0
MemoryStream ms = new MemoryStream();
request.FileByteStream.CopyTo(ms);
s.Position = 0;
var zip = Ionic.Zip.ZipFile.Read(ms)

code explanation by line

  1. create new memorysteam for zip library to work with
  2. copy from http request bytestream "request" to memorystream
  3. by now stream position is at end of stream because of copying, so seek it back to start position
  4. actually call zip on memorystream, done

this extra step is needed since ionic zip not support working on stream directly

WallSky Blue
  • 211
  • 2
  • 7