如何在C#中创建tar.gz文件

12


我已经尝试使用SevenZipLibSevenZipSharp,但都没有成功。 有人能否提供一个使用任何免费库将文本文件归档到 tar.gz 的工作示例呢? 我知道这不是最好的压缩方式,但这是我的要求。


你提供的这两个库都支持tar和gz格式,尽管它们比较老。你遇到了具体的问题吗? - Panagiotis Kanavos
3个回答

15

在NuGet中最受欢迎的支持TAR格式的软件包可能是SharpZipLib。它的维基页面包括使用tar.gz文件的示例,包括创建示例。链接的示例将整个文件夹归档。

如果要对单个文件进行归档,则可以简化示例如下:

private void CreateTarGZ(string tgzFilename, string fileName)
{
    using (var outStream = File.Create(tgzFilename))
    using (var gzoStream = new GZipOutputStream(outStream))
    using (var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream))
    {
        tarArchive.RootPath = Path.GetDirectoryName(fileName);

        var tarEntry = TarEntry.CreateEntryFromFile(fileName);
        tarEntry.Name = Path.GetFileName(fileName);

        tarArchive.WriteEntry(tarEntry,true);
    }
}
基本上,您需要为想要存储的每个文件和文件夹创建一个TarEntry

我已经成功更改了需求并使用zip文件进行工作,但我相信你的答案也可以奏效... - Stavros

4

我不喜欢SharpZipLib提供的有关如何压缩目录的 示例,因为它们的方法并未保留要转换为 .tgz 的目录中的文件夹结构,而是复制了通往该目录的文件夹路径。

例如:

如果您要压缩位于//filer/folder1/folderAfolderA(其中包含一个名为foo.c的单个文件),那么在将folderA转换成.tgz后,在 .tgz 文件中,foo.c所在的路径将是:

folderA.tgz/filer/folder1/foo.c

这个解决方案省略了.tgz文件中的额外文件,结果为:

folderA.tgz/foo.c

using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;

/// <summary>
/// Creates a .tgz file using everything in the sourceDirectory. The .tgz file will be titled {tgzFileName}.tgz and will be located in targetDirectory.
/// </summary>
/// <param name="sourceDirectory">Directory to compress into a .tgz</param>
/// <param name="tgzFileName">Name of .tgz file</param>
/// <param name="targetDirectory">Directory where {tgzFileName}.tgz should be located.</param>
/// <param name="deleteSourceDirectoryUponCompletion">Will delete sourceDirectory if <see langword="true"/></param>
/// <returns>Path to .tgz file</returns>
public string CreateTGZ(string sourceDirectory, string tgzFileName, string targetDirectory, bool deleteSourceDirectoryUponCompletion = false)
{
    if (!tgzFileName.EndsWith(".tgz"))
    {
        tgzFileName = tgzFileName + ".tgz";
    }
    using (var outStream = File.Create(Path.Combine(targetDirectory, tgzFileName)))
    using (var gzoStream = new GZipOutputStream(outStream))
    {
        var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream);

        // Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
        // and must not end with a slash, otherwise cuts off first char of filename
        tarArchive.RootPath = sourceDirectory.Replace('\\', '/');
        if (tarArchive.RootPath.EndsWith("/"))
        {
            tarArchive.RootPath = tarArchive.RootPath.Remove(tarArchive.RootPath.Length - 1);
        }

        AddDirectoryFilesToTGZ(tarArchive, sourceDirectory);

        if (deleteSourceDirectoryUponCompletion)
        {
            File.Delete(sourceDirectory);
        }

        var tgzPath = (tarArchive.RootPath + ".tgz").Replace('/', '\\');

        tarArchive.Close();
        return tgzPath;
    }
}

private void AddDirectoryFilesToTGZ(TarArchive tarArchive, string sourceDirectory)
{
    AddDirectoryFilesToTGZ(tarArchive, sourceDirectory, string.Empty);
}

private void AddDirectoryFilesToTGZ(TarArchive tarArchive, string sourceDirectory, string currentDirectory)
{
    var pathToCurrentDirectory = Path.Combine(sourceDirectory, currentDirectory);

    // Write each file to the tgz.
    var filePaths = Directory.GetFiles(pathToCurrentDirectory);
    foreach (string filePath in filePaths)
    {
        var tarEntry = TarEntry.CreateEntryFromFile(filePath);

        // Name sets where the file is written. Write it in the same spot it exists in the source directory
        tarEntry.Name = filePath.Replace(sourceDirectory, "");

        // If the Name starts with '\' then an extra folder (with a blank name) will be created, we don't want that.
        if (tarEntry.Name.StartsWith('\\'))
        {
            tarEntry.Name = tarEntry.Name.Substring(1);
        }
        tarArchive.WriteEntry(tarEntry, true);
    }

    // Write directories to tgz
    var directories = Directory.GetDirectories(pathToCurrentDirectory);
    foreach (string directory in directories)
    {
        AddDirectoryFilesToTGZ(tarArchive, sourceDirectory, directory);
    }
}

代码中有一个小错误,返回的值不是“.tgz文件路径”,而是带有.tgz扩展名的源目录路径。.tgz文件创建在由'targetDirectory'参数指定的文件夹中。修复方法可以将“return tgzPath;”替换为“return targetDirectory + Path.GetFileName(tgzPath);”。 - user2199593

-1
以下解决方案可能也适用: 如何在C#中创建Tar GZipped文件 我没有测试过,因为毕竟我不打算使用tar.gz文件,但是看起来很详细,人们说它有效。

这个链接中的示例使用了与 Panagiotis Kanavos 的答案相同的包。 - Window

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接