using System;
using System.Collections.Generic;
using System.Text;
using System.IO; // for Stream object
using System.IO.Compression; // for DeflateStream and GZipStream

namespace SqlFuncCompression
{
public enum eCompressMethod : byte
{
Deflate = 1,
Gzip = 2
}

class CompressWrapper
{
const int CHUNKSIZE = 4096;
public static void Compress(Stream input, Stream output, eCompressMethod
CompressMethod)
{
Stream zipStream = null;
try
{
if (CompressMethod == eCompressMethod.Deflate)
{
zipStream = new DeflateStream(output, CompressionMode.Compress);
}
else if (CompressMethod == eCompressMethod.Gzip)
{
zipStream = new GZipStream(output, CompressionMode.Compress);
}
CopyStream(input, zipStream);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (!(zipStream == null))
{
zipStream.Close();
zipStream = null;
}
}
}

public static void Decompress(Stream input, Stream output, eCompressMethod
CompressMethod)
{
Stream zipStream = null;
try
{
if (CompressMethod == eCompressMethod.Deflate)
{
zipStream = new DeflateStream(input, CompressionMode.Decompress);
}
else if (CompressMethod == eCompressMethod.Gzip)
{
zipStream = new GZipStream(input, CompressionMode.Decompress);
}
CopyStream(zipStream, output);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (!(zipStream == null))
{
zipStream.Close();
zipStream = null;
}
}
}

private static void CopyStream(Stream input, Stream output)
{
byte[] bytes = new byte[CHUNKSIZE];
int n;
while (true)
{
n = input.Read(bytes, 0, bytes.Length);
if (n == 0)
{
return;
}
output.Write(bytes, 0, n);
}
}
}
}