Skip Navigation LinksHome > View Post

Save space with System.IO.Compression

New to .NET 2.0, the System.IO.Compression namespace is very cool.

Using the GZipStream it only took these few lines of code to take a file and compress it to a neighbouring file with an extra .gz extension.

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

...

public void CompressFile(string filename)
{    
    using (FileStream fs = new FileStream(filename + ".gz", FileMode.Create, FileAccess.Write, FileShare.None))
    using (GZipStream compressor = new GZipStream(fs, CompressionMode.Compress, true)
    {
        byte[] buffer = File.ReadAllBytes(filename);
        compressor.Write(buffer, 0, buffer.Length);
    }
}

How easy is that? Nice.

Tags: .NET

 
Josh Post By Josh Twist
1:18 AM
13 Jun 2006

» Next Post: SSIS Compress File Task
« Previous Post: Assembly Initialize and CleanUp in Test Projects

Comments are closed for this post.

Posted by Abishek Bellamkonda @ 20 Jun 2006 11:23 PM
It very intresting to see that .NET has built in compression in library. A very good find.

Too bad it can't compress files larger than 4GB ( ISO files and so forth ). But still its good enough.

Posted by Quentin @ 18 Dec 2008 11:47 AM
Do you have an equivalent CompressFile subroutine for VB .NET?

Posted by Mahesh @ 10 Dec 2011 4:01 AM
I am facing actual issue while unzipping the file manually, zipped through SSIS with the above code. I can manually extract the file however its extracting WITHOUT its extension.

Any idea?

Thanks in advance,

© 2005 - 2014 Josh Twist - All Rights Reserved.