Use C# Unzip a bzip2 File

bzip2 is a free and open-source file compression program that uses the Burrows–Wheeler algorithm. It only compresses single files and is not a file archiver. It is used by Wikimedi and its related properties to provide database backup dumps in a compressed format.

You can decompress a bzip2 file using the ICSharpCode.SharpZipLib package available on Nuget. With the ICSharpCode.SharpZipLib reference added to your project, the following method will unzip the file:

using System.IO;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Core;


public static FileInfo Decompress(string bzip2FilePath, string targetDirectory)
    var buffer = new byte[4096];

    using (Stream streamIn = new FileStream(bzip2FilePath, FileMode.Open, FileAccess.Read))
    using (var gzipStream = new BZip2InputStream(streamIn))
        var fileName = Path.GetFileNameWithoutExtension(bzip2FilePath);

        if (string.IsNullOrEmpty(fileName))
            return null;

        var path = Path.Combine(targetDirectory, fileName);

        using (var fileStreamOut = File.Create(path))
            StreamUtils.Copy(gzipStream, fileStreamOut, buffer);

        return new FileInfo(path);
Tagged on: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *