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
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();
}
}
}
}
-
How could you identify the "theOneIWant" entry? I thought you would have to find it by name, is there another way? :)– FaradayJul 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– ThomasJul 31, 2012 at 13:49
-
-
@SarangBorude outputStream could be any stream you can write to, either a memory stream or a file stream.– ThomasOct 27, 2020 at 13:05
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();
}