adamhathcock / sharpcompress

SharpCompress is a fully managed C# library to deal with many compression types and formats.
MIT License
2.22k stars 476 forks source link

[Help] [Question] How to create a .tar.gz file? #760

Open SuperJMN opened 9 months ago

SuperJMN commented 9 months ago

Hi!

I want to create a tar.gz, but seeing the API I can't figure out how.

Thanks :)

BTW, I'm looking to create .deb packages from .NET (without external tools) and I saw that deb files are just tar.gz archives. That's ultimately what I want to do.

btomblinson commented 9 months ago

Check GZipWriterTests, that has an example of writing a tar to a .gz, I don’t think there are any examples of creating the .tar first though

adamhathcock commented 9 months ago

it should be just matter of selecting compression type with the TarWriter or TarArchive https://github.com/adamhathcock/sharpcompress/blob/master/tests/SharpCompress.Test/Tar/TarWriterTests.cs

SuperJMN commented 8 months ago

it should be just matter of selecting compression type with the TarWriter or TarArchive https://github.com/adamhathcock/sharpcompress/blob/master/tests/SharpCompress.Test/Tar/TarWriterTests.cs

I've tried with this, but I didn't get the desired results.

 [Fact]
 public void Test1()
 {
     var tarfile = SharpCompress.Archives.Tar.TarArchive.Create();
     using (var memoryStream = new MemoryStream("Some content"u8.ToArray()))
     {
         var entry = tarfile.AddEntry("something.txt", memoryStream);
         using (FileStream fileStream = File.OpenWrite("Myfile.tar.gz"))
         {
             tarfile.SaveTo(fileStream, new TarWriterOptions(CompressionType.GZip, true));
         }
     }
 }
  1. Since I'm making a tar.gz for a Debian package, I would like the unique entry of the tar.gz file to be one named "." (dot). I don't know how to do that :(
  2. The entry I've created is empty.

I hope anyone can shed a big of light. Thanks a lot!

adamhathcock commented 8 months ago

make sure you're disposing everything....that Test1 isn't

SuperJMN commented 8 months ago

OK, the problem doesn't seem to be related with the disposal, but with the way I added the entry:

    tarfile.AddEntry("something.txt", memoryStream);

as opposed to

    tarfile.AddEntry("something.txt", memoryStream, memoryStream.Length);

Now it works.

DannyBoyk commented 5 months ago

If you are working with a set of files in a directory, we found this works really well:

public static void TarGzDirectory(string inputDirectory, string outputFilePath)
{
    var writerOptions = new WriterOptions(SharpCompress.Common.CompressionType.GZip)
    {
        LeaveStreamOpen = true,
    };

    using (var stream = File.OpenWrite(outputFilePath))
    using (var writer = WriterFactory.Open(stream, SharpCompress.Common.ArchiveType.Tar, writerOptions))
    {
        writer.WriteAll(inputDirectory, "*", SearchOption.AllDirectories);
    }
}