Compress Stream - CSharp System.IO.Compression

CSharp examples for System.IO.Compression:Zip

Description

Compress Stream

Demo Code


using System.Diagnostics;
using System.IO.Compression;
using System.IO;/*from   ww  w.j  av a2s . c  om*/
using System.Text;
using System.Collections.Generic;
using System;

public class Main{
   public static Stream CompressStream(Stream instream) {
         MemoryStream outstream = new MemoryStream((int)instream.Length);
         DeflateStream comp = new DeflateStream(outstream, CompressionMode.Compress, true);

         int numBytes;
         byte[] buffer = new byte[4096];
         while ((numBytes = instream.Read(buffer, 0, 4096)) != 0) {
            comp.Write(buffer, 0, numBytes);
         }
         comp.Flush();
         comp.Dispose();

         // return to the beginning of the stream
         outstream.Position = 0;

         //Debug.WriteLine("Compression: " + instream.Length.ToString() + " to " + outstream.Length.ToString());
         return outstream;
      }
}

Related Tutorials