Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File compression in .net framework 4.0 c#

Tags:

c#

zip

.net-4.0

Are there any built-in classes/examples for version 4.0 to compress specific files from a directory? I found an example on MSDN which uses the compression class but it is only for version 4.5 & above.

like image 259
user2385057 Avatar asked Jun 13 '13 11:06

user2385057


2 Answers

You can use GZipStream and DeflateStream classes which includes also .NET Framework 4.

Check How to: Compress Files from MSDN.

Use the System.IO.Compression.GZipStream class to compress and decompress data. You can also use the System.IO.Compression.DeflateStream class, which uses the same compression algorithm; however, compressed GZipStream objects written to a file that has an extension of .gz can be decompressed using many common compression tools.

An example from here:

Compressing a file using GZipStream

FileStream sourceFileStream = File.OpenRead("sitemap.xml");
FileStream destFileStream = File.Create("sitemap.xml.gz");

GZipStream compressingStream = new GZipStream(destFileStream,
    CompressionMode.Compress);

byte[] bytes = new byte[2048];
int bytesRead;
while ((bytesRead = sourceFileStream.Read(bytes, 0, bytes.Length)) != 0)
{
    compressingStream.Write(bytes, 0, bytesRead);
}

sourceFileStream.Close();
compressingStream.Close();
destFileStream.Close();

Decompressing a file using GZipStream

FileStream sourceFileStream = File.OpenRead("sitemap.xml.gz");
FileStream destFileStream = File.Create("sitemap.xml");

GZipStream decompressingStream = new GZipStream(sourceFileStream,
    CompressionMode.Decompress);
int byteRead;
while((byteRead = decompressingStream.ReadByte()) != -1)
{
    destFileStream.WriteByte((byte)byteRead);
}

decompressingStream.Close();
sourceFileStream.Close();
destFileStream.Close();
like image 197
Soner Gönül Avatar answered Oct 22 '22 11:10

Soner Gönül


I've done a lot of file compression work over the years and by far the best option I found is to use DotNetZip

http://dotnetzip.codeplex.com

Better than GZipStream and the other BCL offerings. It has a friendly API and provides significant functionality.

like image 44
0b101010 Avatar answered Oct 22 '22 13:10

0b101010