Is it possible to zip to NetworkStream?

Jul 5, 2011 at 8:18 PM

Hello,

I would like my application to zip to a network stream but since a NetworkStream does not support Seek opperations will this not work?

I wrote my application to zip to the stream but the file is always corrupt when its complete.

the code Im using is very simple:

using (ZipFile zip = new ZipFile())
    {
        zip.AddDirectory("C:\\Test\\");
        Socket socket = new Socket(AddressFamily.InterNetwork, 
            SocketType.Stream, ProtocolType.Tcp);
        Socket.Connect(ipAddess, port);
        NetworkStream netStream = new NetworkStream(socket);
        zip.Save(netStream);
        netstream.Flush();
        netStream.Close();
    }
           
Thanks for any input

Coordinator
Jul 5, 2011 at 8:32 PM
Edited Jul 5, 2011 at 8:33 PM

I think your NetworkStream should be in a using clause.  Also, I think that using clause should be outside the using clause for the ZipFile. 

  Socket socket = new Socket(AddressFamily.InterNetwork, 
                             SocketType.Stream, ProtocolType.Tcp);
  Socket.Connect(ipAddess, port);
  using (NetworkStream netStream = new NetworkStream(socket))
  {
      using (ZipFile zip = new ZipFile())
      {
          zip.AddDirectory("C:\\Test");
          zip.Save(netStream);
      }
  }

The ZipFile class can save to a non-seekable stream.

Jul 5, 2011 at 9:18 PM

Great, that worked. If you don't mind me asking, why does that make a difference?

Coordinator
Jul 5, 2011 at 10:29 PM

The ZipFile is IDisposable.  When an instance that supports IDisposable is created in a using clause, the .Dispose() is invoked on it, at the closing curly brace. Not quite exactly - there is a try/finally in there, but that's the best way to think about it.  Within the ZipFile.Dispose(), it calls .Close() on any stream that it had written to.  In your code, that stream was already closed, because you explicitly called .Flush() and .Close() on the NetworkStream.  It makes sense to call .Close() on the ZipFile before calling .Close() on the NetworkStream that the zipfile was being saved into.

As for why specifically it did not work the way you did it, I don't know. I don't know exactly what the flow was, or what bytes may have been missing from the NetworkStream.  I just know that it makes sense to me, to treat the ZipFile as the "inner stream" and the NetworkStream as an "outer stream"; this then dictates the order of the using clauses.