LoginSignup
9
9

More than 5 years have passed since last update.

C#におけるtar.gz

Last updated at Posted at 2014-08-19

メモ

SharpZipLib使った
SharpCompressと迷ったが、SharpZipLibの方が利用されてそうだったので。
最近更新されてないようなので不安はあるが...

課題

.gzファイル作る時にファイルの更新日時保持しないようなのでどうしようか悩んでいる

gzip作成

using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;

public void CreateGz(string outputFilePath, string inputFilePath)
{
    using (FileStream infs = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read))
    using (FileStream outfs = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
    using (GZipOutputStream gzipStream = new GZipOutputStream(outfs))
    {
        gzipStream.SetLevel(1);// 圧縮レベル: デフォルト6で遅いので強制的に1にセット
        try
        {
            infs.CopyTo(gzipStream);
        }
        catch
        {
            throw;// 例外処理
        }
    }
}

tar.gz作成

using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.Tar;

public void CreateTarGz(string outputTarFilePath, string sourceDirectory)
{
    using (FileStream fs = new FileStream(outputTarFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
    using (GZipOutputStream gzipStream = new GZipOutputStream(fs))
    {
        gzipStream.SetLevel(1);
        using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzipStream))
        {
            try
            {
                Directory.EnumerateFiles(sourceDirectory)
                    .ToList()
                    .ForEach(x =>
                    {
                        var tarEntry = TarEntry.CreateEntryFromFile(x);
                        tarEntry.Name = Path.GetFileName(x);
                        tarArchive.WriteEntry(tarEntry, false);
                    });
            }
            catch
            {
                throw;
            }
        }
    }
}

9
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9