9 Mayıs 2011 Pazartesi

DeflateStream ile Compress ve Decompress

Byte türündeki dataları sıkıştırmaya yarayan DeflateStream ile yazılan Compress ve Decompress Methodları...

using System.IO;
using System.IO.Compression;
using System;

public static class Deflate
    {
        public static byte[] Compress(byte[] Bytes)
        {
            if (Bytes == null)
                throw new ArgumentNullException("Bytes");
            using (MemoryStream Stream = new MemoryStream())
            {
                using (DeflateStream ZipStream = new DeflateStream(Stream, CompressionMode.Compress, true))
                {
                    ZipStream.Write(Bytes, 0, Bytes.Length);
                    ZipStream.Close();
                    return Stream.ToArray();
                }
            }
        }

        public static byte[] Decompress(byte[] Bytes)
        {
            if (Bytes == null)
                throw new ArgumentNullException("Bytes");
            using (MemoryStream Stream = new MemoryStream())
            {
                using (DeflateStream ZipStream = new DeflateStream(new MemoryStream(Bytes), CompressionMode.Decompress, true))
                {
                    byte[] Buffer = new byte[4096];
                    while (true)
                    {
                        int Size = ZipStream.Read(Buffer, 0, Buffer.Length);
                        if (Size > 0) Stream.Write(Buffer, 0, Size);
                        else break;
                    }
                    ZipStream.Close();
                    return Stream.ToArray();
                }
            }
        }

Hiç yorum yok:

Yorum Gönder