C# と VB.NET の質問掲示板

わんくま同盟

ASP.NET、C++/CLI、Java 何でもどうぞ

C# と VB.NET の入門サイト


■103870 / )  Re[1]: 1ファイルのパスワード付きZIP圧縮
□投稿者/ 魔界の仮面弁士 (3901回)-(2025/10/21(Tue) 19:56:13)
No103868 (furu さん) に返信
> VS2026 C# .NetFramework4.8

Visual Studio 2026 Insiders ですか?
まだ試してないや…。


> 久々にZIP圧縮しようとしたら
> なかなかいい方法が見つかりません。
7za.exe を Process.Start で呼んだら駄目ですか?

コマンドライン的には
 7za a -tzip -pYourPassword archive.zip target.txt
ですよね。


7-Zip CLI の場合はこんな感じ。

// パスワード付き zip にする方法
var psi = new ProcessStartInfo {
  FileName = "7z.exe",
  Arguments = $"a -tzip -pYourPassword secure.zip target.txt",
  RedirectStandardOutput = true,
  UseShellExecute = false
};
Process.Start(psi);

自己解凍にする場合は バッチ処理的に言えば
 copy /b 7z.sfx + config.txt + archive.7z archive.exe
に相当する追加処理を行うことで実装できます。



別プロセスにしたくないなら、SevenZipSharp ってのもあります(7z.dll 依存)。
ただし AES 暗号化はサポートするものの、AES256 に非対応だったかな。
https://qiita.com/koshian2/items/f648892f37cddaab7093


> SharpZipLib
>   1ファイルのやり方がわからない

こちらは 7z.dll に依存せずに済みますね。

// using ICSharpCode.SharpZipLib.Zip;

string inputFile = @"C:\Sample\圧縮対象ファイル.TXT";
string outputZip = @"C:\Sample\出力先.ZIP";
string password = "YourPassword";

// FileStream の代わりに MemoryStream を使えば、オンメモリで処理することもできる
using (FileStream fsOut = File.Create(outputZip))
using (ZipOutputStream zipStream = new ZipOutputStream(fsOut))
{
  zipStream.SetLevel(9); // 圧縮率(0〜9)
  zipStream.Password = password;
  zipStream.UseZip64 = UseZip64.Off;

  // AES256 暗号化付きエントリを作成
  ZipEntry entry = new ZipEntry(Path.GetFileName(inputFile)) { AESKeySize = 256, DateTime = DateTime.Now };
  zipStream.PutNextEntry(entry); // 複数ファイルを追加する場合は PutNextEntry を繰り返す
  using (FileStream fsIn = File.OpenRead(inputFile))
  {
    fsIn.CopyTo(zipStream);
  }
  zipStream.CloseEntry();
}


有償でも良ければ、他にもいくつかのライブラリがあるみたいです。
返信 編集キー/


管理者用

- Child Tree -