Recursive AI

Compress and decompress bzip2 in C#

OneArchive is a free, open-source archive and compression library for .NET from Recursive AI: archives (zip, tar, 7z, RAR 5, cpio, ar, ISO) in RecursiveAI.OneArchive, codecs (zlib, gzip, xz, Zstandard, Brotli) in RecursiveAI.OneCompress. MIT or Apache-2.0, no native dependencies.

Bzip2 compresses one byte stream into a .bz2 file. Use it for a single file, or compress a tar archive when you need to keep several files together.

Terminal
dotnet add package RecursiveAI.OneCompress

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneCompress.BZip2;
 
byte[] packed = BZip2.Compress("Hello!"u8);
byte[] restored = BZip2.Decompress(packed);
Console.WriteLine(
    System.Text.Encoding.UTF8.GetString(restored));
Text
Hello!

Unzip the example, then dotnet run.

The full program

The program generates message.txt: the text Hello from BZip2! followed by a newline, repeated 100 times. It writes message.txt.bz2 and restored.txt, then compares the bytes. It replaces these sample files on each run.

C#
using RecursiveAI.OneCompress.BZip2;
using System.Text;
 
byte[] original = Encoding.UTF8.GetBytes(
    string.Concat(Enumerable.Repeat("Hello from BZip2!\n", 100)));
File.WriteAllBytes("message.txt", original);
byte[] packed = BZip2.Compress(original);
File.WriteAllBytes("message.txt.bz2", packed);
byte[] restored = BZip2.Decompress(
    File.ReadAllBytes("message.txt.bz2"),
    new BZip2DecompressionOptions { MaxOutputSize = 1024 * 1024 });
File.WriteAllBytes("restored.txt", restored);
Console.WriteLine($"Input: {original.Length} bytes");
Console.WriteLine($"Compressed: {packed.Length} bytes");
Console.WriteLine($"Restored: {restored.Length} bytes");
Console.WriteLine($"Bytes match: {original.SequenceEqual(restored)}");

dotnet run prints:

Text
Input: 1800 bytes
Compressed: 87 bytes
Restored: 1800 bytes
Bytes match: True

Invalid or truncated compressed data raises CompressionFormatException; exceeding a decoder limit raises CompressionLimitException.

Variations

Choose block-size level 1 and cap restored output at 1 KiB.

C#
using RecursiveAI.OneCompress.BZip2;
 
byte[] packed = BZip2.Compress("Hello!"u8,
    new BZip2Options { Level = 1 });
byte[] restored = BZip2.Decompress(packed,
    new BZip2DecompressionOptions { MaxOutputSize = 1024 });
Console.WriteLine(restored.Length);
Text
6

The short answer

To compress and decompress bzip2 in C#, install RecursiveAI.OneCompress and use BZip2.Compress and BZip2.Decompress from RecursiveAI.OneCompress.BZip2. The first method returns a complete bzip2 stream. The second restores the uncompressed bytes. Write the compressed result with File.WriteAllBytes to make a .bz2 file. The package is managed C# and needs no native codec installation.

The full program above deliberately reads back the file it wrote, rather than decoding the byte array still in memory. It compares the restored bytes with the original, so a successful run means the disk round trip preserved the data. The compression size printed here describes only this small, repetitive sample, not a predicted ratio for your files.

How do I decompress a bzip2 file?

Read the file as bytes, pass them to BZip2.Decompress, then write or interpret the returned bytes. The full program does exactly that for message.txt.bz2. For text, use the same encoding that produced the original bytes. For images or other binary data, save the bytes directly; a text decoder is not part of decompression.

Set BZip2DecompressionOptions.MaxOutputSize to the largest uncompressed payload your application expects. The default is 1 GiB, not the size of the compressed file. A small compressed input can produce much more output. The one-call method allocates the returned array, so choose a cap that fits your application’s memory budget as well as its file-size requirements.

The decoder accepts concatenated bzip2 streams and joins their output. This matters for files produced by tools that concatenate independently compressed chunks: do not stop after the first chunk. Checksums are verified by default. Truncation, corruption and unexpected trailing bytes are errors, rather than a reason to quietly return partial data.

How do I decompress a tar.bz2 file?

There are two layers: bzip2 compression on the outside, and tar entries on the inside. Calling BZip2.Decompress removes only the outer layer. Its output is still a tar archive, not a directory of extracted files. A .bz2 extension by itself does not mean that the content is tar.

Use the archive API in RecursiveAI.OneArchive when you need to extract the files inside a compressed tar. It handles archive entries rather than just restoring a byte stream. The compressed-tar extraction recipe shows that API. Keep the distinction when naming your own output: compressing message.txt gives message.txt.bz2; it does not make a tar archive.

For writing, bzip2 options expose Level from 1 through 9, with 9 as the default. It controls the block-size level in the stream header. It is not a target file size. MaxCodeLength controls the longest Huffman code, with a default of 17 and an accepted range of 9 through 20. Start with defaults unless your application has a specific reason to change them; neither setting guarantees that arbitrary input becomes smaller.

All onearchive recipes