Last active
June 13, 2023 15:52
-
-
Save shirobusa1997/ee62a0794bdc61260b56d59a850d5139 to your computer and use it in GitHub Desktop.
Create TGZ Archive file with SharpZipLib in UnityEngine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Standard Namespaces | |
using System; | |
using System.IO; | |
// SharpZipLib Namespaces | |
using ICSharpCode.SharpZipLib.Tar; | |
using ICSharpCode.SharpZipLib.GZip; | |
// UnityEngine Namespaces | |
using UnityEngine; | |
// Package Namespaces | |
namespace MJTStudio | |
{ | |
/// <summary> | |
/// パッケージのアーカイブ関係の処理を提供するライブラリクラスです。 | |
/// </summary> | |
public static class ArchiverLibrary | |
{ | |
/// <summary> | |
/// 指定されたパスのファイルをTarアーカイブ化し、GZip形式で圧縮します。 | |
/// </summary> | |
/// <param name="destPath">圧縮ファイル作成先のパス</param> | |
/// <param name="targetPaths">Tarアーカイブ・圧縮を行う対象のパス</param> | |
/// <param name="isRecursive">配下ディレクトリのファイルも再帰的にTarアーカイブ化するかどうか</param> | |
/// <param name="compressionLevel">圧縮レベル (初期値:1)</param> | |
/// <returns></returns> | |
public static bool CompressDirectoriesToTgz( | |
string destPath, | |
string[] targetPaths, | |
bool isRecursive, | |
int compressionLevel = 1 | |
) | |
{ | |
// 圧縮ファイル生成のためのストリームを作成する | |
using (FileStream fs = new FileStream(destPath, FileMode.Create, FileAccess.Write, FileShare.None)) | |
// GZip圧縮のためのストリームを作成する | |
using (GZipOutputStream gZipOutputStream = new GZipOutputStream(fs)) | |
{ | |
// 圧縮レベルを設定する | |
gZipOutputStream.SetLevel(compressionLevel); | |
// Tarアーカイブを作成する | |
using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gZipOutputStream, TarBuffer.DefaultBlockFactor)) | |
{ | |
// ファイルのTarアーカイブ化・圧縮を試行する | |
try | |
{ | |
// アーカイブ元のファイルを維持するように設定する | |
tarArchive.SetKeepOldFiles(true); | |
// アーカイブ対象ファイル文字コード変換を行わないように設定する | |
tarArchive.AsciiTranslate = false; | |
// 指定されたパスの数繰り返す | |
foreach (string targetPath in targetPaths) | |
{ | |
// 指定されたパスのファイルをTarアーカイブのエントリとして生成する | |
var tarEntry = TarEntry.CreateEntryFromFile(targetPath); | |
// Tarアーカイブにエントリを追加する | |
tarArchive.WriteEntry(tarEntry, isRecursive); | |
} | |
} | |
// ファイルのアーカイブ中に何らかの例外がスローされた場合の処理 | |
catch (Exception e) | |
{ | |
Debug.LogError( | |
typeof(ArchiverLibrary).Name | |
+ ": ファイルのアーカイブ中に例外がスローされました。\n" | |
+ "RawMessage: " | |
+ e | |
); | |
return false; | |
} | |
// Tarアーカイブのストリームを閉じる | |
tarArchive.Close(); | |
} | |
} | |
// | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment