如何使用 SharpZipLib 提取或访问 gzip 中特定文件的流?

问题描述 投票:0回答:3

如何使用 SharpZipLib 从 tar.gz(tar 文件和文件夹,然后进行 gzip 压缩)中提取特定文件(或具有流式访问)?或者也许有人有一些类似的库可以在 .NET cf 3.5 中执行此操作?

c# compact-framework
3个回答
8
投票
using ( FileStream inputStream = File.OpenRead ( aPackage ) )
{
    using ( GzipInputStream gzStream = new GzipInputStream ( inputStream ) )
    {
        using ( TarInputStream tarStream = new TarInputStream ( gzStream ) )
        {
            TarEntry entry = tarStream.GetNextEntry();
            while ( entry != null )
            {
                if ( entry == theOneIWant )
                {
                    tarStream.CopyEntryContents (outputStream );
                    break;
                }
                entry = tarStream.GetNextEntry();
            }
        }
    }
}

0
投票

这应该适合你。

public static void Main(string[ args)
{
    TarInputStream tarIn = new TarInputStream(new FileStream(@args[0], FileMode.Open, FileAccess.Read));
    TarEntry curEntry = tarIn.GetNextEntry();
    while (curEntry != null)
    {
        if (curEntry.Name.EndsWith("foo.txt", StringComparison.CurrentCultureIgnoreCase))
        {
            byte[] outBuffer = new byte[curEntry.Size];
            FileStream fs = new FileStream(@"foo.txt", FileMode.Create, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            tarIn.Read(outBuffer, 0, (int)curEntry.Size);
            bw.Write(outBuffer,0,outBuffer.Length);
            bw.Close();
        }
        curEntry = tarIn.GetNextEntry();
    }
    tarIn.Close();
}

0
投票

除了原始答案之外,还举例说明如何在流中解析

TarEntry
。这个可以复制空文件夹的层次结构或跳过它


const string prefix = "./"; // sometimes when it comes from Linux
...
// using (.. here
...

TarEntry entry = tarStream.GetNextEntry();
while (entry != null)
{

    string? fileOrFolder;
    if (entry.Name.StartsWith(prefix))
        fileOrFolder = Path.Combine(outDir, entry.Name.Substring(prefix.Length));
    else
        fileOrFolder = entry.Name;

    if (entry.IsDirectory)
    {
        if (createEmptyDirs)
        {
            if (!Directory.Exists(fileOrFolder))
                Directory.CreateDirectory(fileOrFolder);
        }
    }
    else
    {

        string dir = Path.GetDirectoryName(fileOrFolder);

        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        using (FileStream fileStream = new FileStream(fileOrFolder, FileMode.Create))
        {
            tarStream.CopyEntryContents(fileStream);
            tarStream.Flush();
            fileStream.Flush();
        }
    }

    entry = tarStream.GetNextEntry();

.........
// close usings here
.........
© www.soinside.com 2019 - 2024. All rights reserved.