marnun
marnun

Reputation: 808

When using SharpZipLib- Unable to extract tar.gz files from MemoryStream

I need to do so since I'm running from azure Webjob. here is my code:

public static void ExtractTGZ(Stream inStream)
{
    using (Stream gzipStream = new GZipInputStream(inStream))
    {
        using (var tarIn = new TarInputStream(gzipStream))
        {
            TarEntry tarEntry;
            tarEntry = tarIn.GetNextEntry();
            while (tarEntry != null)
            {
                Console.WriteLine(tarEntry.Name);
                tarEntry = tarIn.GetNextEntry();
            }   
        }
    }
}

when calling ExtractTGZ, I'm doing so with MemoryStream when getting to the "GetNextEntry", the "tarEntry" is null, but when using FileStream instead of the MemoryStream I get values

Upvotes: 3

Views: 1848

Answers (1)

Tim S.
Tim S.

Reputation: 56536

Your MemoryStream most likely is not at the right Position to be read. For example, if your code is something like this:

using (var ms = new MemoryStream())
{
    otherStream.CopyTo(ms);
    //ms.Position is at the end, so when you try to read, there's nothing to read
    ExtractTGZ(ms);
}

You need to move it to the beginning using the Seek method or the Position property:

using (var ms = new MemoryStream())
{
    otherStream.CopyTo(ms);
    ms.Seek(0, SeekOrigin.Begin); // now it's ready to be read
    ExtractTGZ(ms);
}

Also, your loop would be more concise and, I'd argue, clearer, if written like this:

TarEntry tarEntry;
while ((tarEntry = tarIn.GetNextEntry()) != null)
{
    Console.WriteLine(tarEntry.Name);
}

Upvotes: 3

Related Questions