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
01:18
13 Jun 2006

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

Comments:

Posted by Abishek Bellamkonda @ 20 Jun 2006 23:23
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
Do you have an equivalent CompressFile subroutine for VB .NET?

Post a comment:

Name  

E-mail (never shared)

URL

Comments  

Captcha ImageRefresh Image
What's this?
Enter code above