2

How to extract specific file (or have streamed access) from tar.gz (tar files and folders and then gzipped) using SharpZipLib? Or maybe anyone has some similar library to do that in .NET cf 3.5?

2 Answers 2

7
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();
            }
        }
    }
}
4
  • How could you identify the "theOneIWant" entry? I thought you would have to find it by name, is there another way? :)
    – Faraday
    Jul 31, 2012 at 13:24
  • @Vijay by using any of the properties of TarEntry, which most likely would be Name (or File.) Can't make it too easy now, can I? :D
    – Thomas
    Jul 31, 2012 at 13:49
  • What is the outputStream here? how is it initialized? Oct 27, 2020 at 1:37
  • @SarangBorude outputStream could be any stream you can write to, either a memory stream or a file stream.
    – Thomas
    Oct 27, 2020 at 13:05
0

This should do it for you.

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.