Working with BZIP2 Archives

Overview

BZIP2 is a Unix-friendly compression format known for good compression ratio and block-based processing. Aspose.ZIP for .NET provides the Bzip2Archive class to compress or extract a single data stream in .bz2 format.

Because BZIP2 stores one compressed stream rather than a collection of entries, it is best suited for compressing a single file. If you need to package multiple files, first create a TAR container and then compress it as tar.bz2.

Compress a File

Use SetSource to assign the source file or stream, then call Save.

1    using (Bzip2Archive archive = new Bzip2Archive())
2    {
3        archive.SetSource("data.bin");
4        archive.Save("data.bin.bz2");
5    }

Choose Compression Block Size

Bzip2SaveOptions accepts block sizes from 1 to 9. Higher values usually improve compression ratio at the cost of more CPU time and memory.

1    using (FileStream output = File.Open("data.bin.bz2", FileMode.Create))
2    using (FileStream source = File.Open("data.bin", FileMode.Open, FileAccess.Read))
3    using (Bzip2Archive archive = new Bzip2Archive())
4    {
5        archive.SetSource(source);
6        archive.Save(output, new Bzip2SaveOptions(9));
7    }

For large files, BZIP2 compression can also run in parallel. See parallel bzip2 compression for the CompressionThreads option.

Extract a BZIP2 Archive

You can open a .bz2 archive from a file path or stream and extract the decompressed data to any writable stream.

1    using (Bzip2Archive archive = new Bzip2Archive("data.bin.bz2"))
2    using (FileStream extracted = File.Create("data.bin"))
3    {
4        archive.Extract(extracted);
5    }

If you prefer to work with the unpacked stream directly, call Open:

1    using (Bzip2Archive archive = new Bzip2Archive("data.bin.bz2"))
2    using (Stream unpacked = archive.Open())
3    using (MemoryStream ms = new MemoryStream())
4    {
5        unpacked.CopyTo(ms);
6    }

Report Extraction Progress

To monitor decompression progress, pass Bzip2LoadOptions and subscribe to ExtractionProgressed.

 1    Bzip2LoadOptions loadOptions = new Bzip2LoadOptions();
 2    loadOptions.ExtractionProgressed += (sender, args) =>
 3    {
 4        Console.WriteLine("{0} bytes extracted", args.ProceededBytes);
 5    };
 6
 7    using (Bzip2Archive archive = new Bzip2Archive("data.bin.bz2", loadOptions))
 8    using (MemoryStream extracted = new MemoryStream())
 9    {
10        archive.Extract(extracted);
11    }

Cancel Extraction

If decompression may need to be interrupted, provide a CancellationToken in Bzip2LoadOptions.

 1    using (CancellationTokenSource cts = new CancellationTokenSource())
 2    {
 3        cts.CancelAfter(TimeSpan.FromSeconds(60));
 4
 5        try
 6        {
 7            using (Bzip2Archive archive = new Bzip2Archive("big.bz2",
 8                new Bzip2LoadOptions() { CancellationToken = cts.Token }))
 9            using (MemoryStream extracted = new MemoryStream())
10            {
11                archive.Extract(extracted);
12            }
13        }
14        catch (OperationCanceledException)
15        {
16            Console.WriteLine("Extraction was cancelled.");
17        }
18    }

Cancellation can leave partial data in the destination stream, so if you need all-or-nothing behavior, extract to a temporary target and discard it on cancellation.

Create a tar.bz2 Archive

To compress multiple files with BZIP2, first collect them into a TAR archive and then save that TAR stream through Bzip2Archive.

 1    using (FileStream output = File.Open("result.tar.bz2", FileMode.Create))
 2    using (TarArchive tar = new TarArchive())
 3    {
 4        tar.CreateEntry("alice29.txt", "alice29.txt");
 5        tar.CreateEntry("fields.c", "fields.c");
 6
 7        using (Bzip2Archive archive = new Bzip2Archive())
 8        {
 9            archive.SetSource(tar, TarFormat.Pax);
10            archive.Save(output, new Bzip2SaveOptions(9));
11        }
12    }
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.