---
title: "Decompress an xz file in C#"
url: https://recursiveai.org/onearchive/cookbook/decompress-xz-file/
description: "xz is a compressed-file container around LZMA2. Decode the container to recover the original file bytes. Runnable C# example using OneCompress."
version: "1.2.0"
---

# Decompress an xz file 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneCompress) · [GitHub](https://github.com/recursive-ai-oss/onearchive-csharp) · [Docs](https://recursiveai.org/onearchive/docs/) · [Download example (.zip)](https://recursiveai.org/onearchive/cookbook/decompress-xz-file/decompress-xz-file.zip)

Decode `sample.txt.xz` (in the zip) to recover `hello xz` and a newline.

```shell
dotnet add package RecursiveAI.OneCompress
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneCompress.Xz;
var packed = File.ReadAllBytes("sample.txt.xz");
byte[] unpacked = Xz.Decompress(packed);
File.WriteAllBytes("restored.txt", unpacked);
Console.WriteLine(unpacked.Length);
```

Writes `restored.txt` and prints its byte count:

```text
9
```

Unzip [the example](https://recursiveai.org/onearchive/cookbook/decompress-xz-file/decompress-xz-file.zip), then `dotnet run`.

## The full program

`sample.txt.xz` is in the download. It was created with `xz --keep sample.txt` from this UTF-8 input, including the final newline:

```text
hello xz
```

The program writes `restored.txt`, compares it with the included `sample.txt`, then deliberately tries a four-byte output limit.

Malformed input throws `CompressionFormatException`; a dictionary or output limit violation throws `CompressionLimitException`. The one-shot decoder finishes before this program writes the output file.

```csharp
using System.Text;
using RecursiveAI.OneCompress;
using RecursiveAI.OneCompress.Xz;

byte[] compressed = File.ReadAllBytes("sample.txt.xz");
byte[] restored = Xz.Decompress(compressed);
File.WriteAllBytes("restored.txt", restored);
Console.Write(Encoding.UTF8.GetString(restored));
Console.WriteLine($"Matches sample.txt: {restored.AsSpan().SequenceEqual(File.ReadAllBytes("sample.txt"))}");
try
{
    Xz.Decompress(compressed, new XzDecompressionOptions { MaxOutputSize = 4 });
}
catch (CompressionLimitException)
{
    Console.WriteLine("4-byte output limit: refused");
}
```

`dotnet run` prints:

```text
hello xz
Matches sample.txt: True
4-byte output limit: refused
```

## Variations

**Set an output limit.** This standalone snippet refuses the nine-byte sample:

```csharp
using RecursiveAI.OneCompress;
using RecursiveAI.OneCompress.Xz;

try
{
    Xz.Decompress(File.ReadAllBytes("sample.txt.xz"),
        new XzDecompressionOptions { MaxOutputSize = 4 });
}
catch (CompressionLimitException)
{
    Console.WriteLine("4-byte output limit: refused");
}
```

```text
4-byte output limit: refused
```

## Related recipes

- [Extract a tar.gz archive](https://recursiveai.org/onearchive/cookbook/extract-tar-gz/)
- [Compress and decompress zlib](https://recursiveai.org/onearchive/cookbook/compress-decompress-zlib/)
- [Create a 7z archive](https://recursiveai.org/onearchive/cookbook/create-7z/)

<!-- article -->

## The short answer

Read the `.xz` file as bytes, call `Xz.Decompress`, and write the returned byte array to your output path. The type is in `RecursiveAI.OneCompress.Xz`. Install `RecursiveAI.OneCompress`; no command-line decompressor is needed to run the C# example.

The download contains a genuine xz stream and its original text. The full program compares the decoded bytes rather than relying on a filename or the appearance of the text. The deliberate limit failure also shows how the API handles output larger than your application permits.

## How can I decompress an xz file?

The snippet at the top handles a complete file in memory. It reads `sample.txt.xz`, decodes it, and writes `restored.txt`. Replace those two paths to process your own file. The sample’s decoded contents are exactly `hello xz` followed by a newline: nine UTF-8 bytes.

`Xz.Decompress` reads the xz container, not merely a raw LZMA payload. The [xz documentation](https://recursiveai.org/onearchive/docs/xz/) describes the LZMA2 layer, block checks and filters. The decoder reads multiple streams and stream padding. It rejects trailing bytes unless you explicitly enable `AllowTrailingData`; leaving that disabled helps distinguish a complete valid file from a valid prefix followed by unexpected input.

There are separate limits for the LZMA2 dictionary and total decoded output. Defaults are 64 MiB for `MaxDictionarySize` and 1 GiB for `MaxOutputSize`. Dictionary declarations above the configured limit are rejected before memory is reserved. The variation sets an intentionally tiny output limit so you can see the exception path with a small fixture. In an application, choose limits based on the files you expect rather than raising them automatically after a failure.

The example holds both compressed and decoded arrays in memory. `MaxOutputSize` bounds the decoder’s output; it does not prevent `File.ReadAllBytes` from first reading a large compressed file. Check input size separately when that matters for your application.

## What do I do with a tar.xz file?

Decompressing `.tar.xz` recovers a tar archive, not its individual files. xz supplies compression; tar supplies the file entries and paths. The [xz manual](https://tukaani.org/xz/man/xz.1.html) describes xz as a single-file compressor and directs users to an archiver when combining multiple files.

If you use the snippet on a tar.xz input, name the result with a `.tar` suffix. Then use an archive reader to list or extract the entries. Don’t interpret the decoded tar bytes as UTF-8 text, and don’t treat an archive’s entry paths as safe output paths without the archive reader’s extraction checks.

## How do I unzip an img.xz file?

Decode the xz layer and save the result as an `.img` file. The output is the disk-image bytes, not a directory of files. The decompression operation is the same as for the text example; only the input and output paths change. Do not run the text conversion from the full program against a binary image.

For large images, determine the expected expanded size before choosing the output limit. A small compressed file can expand beyond the decoder’s default. Keep checksum verification enabled: OneCompress reads CRC-32, CRC-64 and SHA-256 block checks, as well as streams written without a block check. A successful decode recovers bytes; it does not mount the image or write it to a device.
