使用 SharpZipLib 时 - 无法从 MemoryStream 中提取 tar.gz 文件

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

我需要这样做,因为我是从 azure Webjob 运行的。 这是我的代码:

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();
            }   
        }
    }
}

调用 ExtractTGZ 时,我使用的是 MemoryStream 当到达“GetNextEntry”时,“tarEntry”为空,但是当使用 FileStream 而不是 MemoryStream 时,我得到值

您的 MemoryStream 很可能不在正确的位置 Position 无法阅读。例如,如果您的代码是这样的:

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);
}

您需要使用 Seek 方法或 Position 属性:

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

此外,如果这样写,你的循环会更简洁,而且我认为会更清晰:

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