How to unpack a .xz (lzma2) file using sharpcompress

3.5k Views Asked by At

I have downloaded the SharpCompress source code and created a simple console application to decompress a small .xz file. Following several different examples on the github site and other examples here on stackoverflow, I can't find any combinations that actually work for "unzipping" a .xz file, nor any instructions or documentation. Has anyone actually been able to "unzip" a .xz file using SharpCompress?

        using (Stream stream = File.OpenRead(@"C:\temp\ot.xz"))
        {
            using (var reader = ReaderFactory.Open(stream))
            {
                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        Console.WriteLine(reader.Entry.Key);
                        reader.WriteEntryToDirectory(@"C:\temp", new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite = true
                        });
                    }
                }
            }
        }

This particular code throws an exception 'Cannot determine compressed stream type. Supported Reader Formats: Zip, GZip, BZip2, Tar, Rar, LZip, XZ'

The following code works better (doesn't throw an error) but the Entry.Key value is unexpected or gibberish.

        using (Stream stream = File.OpenRead(@"C:\temp\ot.xz"))
        {
            var xzStream = new XZStream(stream);
            using (var reader = TarReader.Open(xzStream))// ReaderFactory.Open(stream))
            {
                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        Console.WriteLine(reader.Entry.Key);
                    }
                }
            }
        }
1

There are 1 best solutions below

2
On BEST ANSWER

As it turns out, both SharpCompress and XZ.NET will work using the same simple client code.

Note however, that one of the files I tested with caused XZ.NET to throw an exception when attempting to read past end of stream, as both examples below do. SharpCompress handled both files correctly.

using (Stream xz = new XZStream(File.OpenRead(@"\temp\server.crt.xz")))
using (Stream stream = new MemoryStream())
{
    xz.CopyTo(stream);
}

Or, for compressed plain text:

using (Stream xz = new XZStream(File.OpenRead(@"\temp\server.crt.xz")))
using (TextReader reader = new StreamReader(xz))
{
    Debug.WriteLine(reader.ReadToEnd());
}