20 September 2007

Compressing files

.Net framework supports two kinds of compressing types: GZipStream and DeflateStream. The different between these types is that the first one allows for headers that include extra information that might be helpful to decompress a file with the widely used gzip tool. Both of them use the same algorithm and both are free of patent protection so you can use them in commercial projects.
Below I will write the method to compress and decompress any data or file with using GZipStream. If you want to use the DeflateStream simply change the type in this code from GZipStream on DeflateStream.

public static void Compressing(string source, string destination)

{

FileStream src = null;

FileStream dest = null;

try

{

src = File.OpenRead(source);

dest = File.Create(destination);

GZipStream compress = new GZipStream(dest, CompressionMode.Compress);

int b = src.ReadByte();

while (b != -1)

{

compress.WriteByte((byte)b);

b = src.ReadByte();

}

}

finally

{

if (src != null)

src.Close();

if (dest != null)

dest.Close();

}

}

public static void Decompress(string source, string destination)

{

FileStream src = null;

FileStream dest = null;

try

{

src = File.OpenRead(source);

dest = File.Create(destination);

GZipStream compress = new GZipStream(src, CompressionMode.Decompress);

int b = compress.ReadByte();

while (b != -1)

{

dest.WriteByte((byte)b);

b = compress.ReadByte();

}

}

finally

{

if (src != null)

src.Close();

if (dest != null)

dest.Close();

}

}

Labels:

0 Comments:

Post a Comment

<< Home