フッターコンテンツにスキップ
IRONZIPの使用

How to Zip Files in Folder Using C#

ZIPファイルは、ZIP形式を使用して1つまたは複数の圧縮ファイルまたはフォルダーを含むファイルです。 複数のファイルやフォルダを1つのファイルに圧縮し、アーカイブする一般的な方法です。データのサイズを減少させ、ディスクスペースを節約し、インターネット上でファイルを転送しやすくします。 この記事では、ZIPファイルをC#で使用してIronZIPライブラリで扱う方法を学びます。 プログラム的にZIPファイルを作成、読み取り、抽出、更新する方法や、IronZIPの暗号化、パスワード保護、圧縮レベルなどのさまざまな機能を使用する方法を紹介します。 この記事の最後までには、IronZIPを使用してC#のアプリケーションでZIPファイルを簡単に扱えるようになります。

この記事で取り上げる内容

  1. プロジェクトにIronZIPをインストール
  2. ZIPファイルを作成
  3. パスワード保護されたZIPファイルを作成
  4. ZIPファイルを抽出
  5. パスワード保護されたZIPファイルを抽出
  6. 既存のZIPアーカイブにアクセス

IronZIPとは何か?

IronZIPは、プログラムでZIPファイルを作成、読み取り、抽出するための強力で多目的なC# ZIPアーカイブライブラリです。 それはZIPTARGZIP、およびBZIP2など、さまざまなアーカイブ形式をサポートしています。 また、パスワード保護、暗号化、および圧縮レベルもサポートしています。 IronZIPは.NET 8、7、6、Core、Standard、Frameworkと互換性があります。

IronZIPは、さまざまなユースケースやZIPファイルの作業の利点を扱うのに役立ちます。

1.バックアップシステムの作成: IronZIPを使用して、重要なファイルやフォルダをZIPアーカイブに圧縮および暗号化し、安全な場所に保存することができます。 この方法でディスクスペースを節約し、不正アクセスからデータを保護することができます。 2.メール添付ファイルの送信: IronZIPを使用すると、メール添付ファイルをZIPファイルに圧縮することでサイズを小さくできます。これにより、ファイルサイズの制限を超えることを回避し、送信処理を高速化できます。

  1. Webからのファイルのダウンロード: IronZIPを使用すると、ソフトウェアパッケージ、ドキュメント、画像、その他の種類のファイルなど、WebからZIPファイルをダウンロードして解凍できます。 これにより、帯域幅と時間を節約し、必要なファイルに簡単にアクセスできます。

IronZIPの始め方

コードを書く前に、C#プロジェクトにIronZIP NuGetパッケージをインストールする必要があります。 IronZIPは、NuGet経由で入手可能な人気のある圧縮ライブラリです。

IronZIPライブラリのインストール

IronZIPをインストールするには、Visual StudioのNuGetパッケージマネージャーコンソールを使用できます。 以下のコマンドを実行するだけです。

Install-Package IronZip

また、公式IronZIPウェブサイトから直接パッケージをダウンロードすることもできます。インストールが完了したら、次の名前空間をC#コードの先頭に追加して始められます。

using IronZip;
using IronZip;
Imports IronZip
$vbLabelText   $csharpLabel

フォルダ内のC# ZIPファイルを作成する

IronZIPを使用してフォルダ内に簡単にZIPファイルを作成できます。次のコードは、指定されたディレクトリからすべてのファイルをZIP化します。

using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
Imports System
Imports System.IO
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Get all files from the specified directory
		Dim fileArray() As String = Directory.GetFiles("D:\Docs\")

		' Create a new ZIP archive
		Using archive = New IronZipArchive()
			' Iterate through each file and add it to the archive
			For Each file In fileArray
				archive.Add(file) ' Add files to the ZIP
			Next file
			' Save the archive to a file
			archive.SaveAs("myZipFile.zip")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

上記のC#コードでは、IronZIPライブラリを使用してすべてのファイルを1つのZIPファイルに圧縮します。このコードは以下のことを行います。

  • 文字列配列 fileArray を宣言し、ディレクトリのパス ("D:\Docs") をパラメータとして渡し、Directory.GetFiles メソッドの結果を代入します。 このメソッドは、指定されたディレクトリ内のすべてのファイルの完全な名前を含む文字列の配列を返します。
  • メモリ上の ZIP アーカイブを表す IronZipArchive クラスの新しいインスタンスを作成します。 インスタンスは変数 archive に代入され、コードブロックが終了した時に ZIP アーカイブが破棄されることを保証する using 文でラップされています。
  • fileArray 配列を foreach ループで反復処理し、各ファイルに対してファイル名をパラメータとして渡し archive オブジェクトの Add メソッドを呼び出します。 このメソッドは、ファイルと同じ名前と内容の新しいエントリをZIPアーカイブに追加します。
  • ZIPファイルの名前("myZipFile.zip")をパラメータとして渡し archive オブジェクトの SaveAs メソッドを呼び出します。 このメソッドは、現在のファイルシステムにZIPアーカイブをファイルとして保存します。

このようにして、少しのコードで新しいZIPアーカイブを簡単に作成できます。

出力

出力は次の通りです。

フォルダー内のファイルをC#でZIPする方法: 図1 - 前のコード例からの出力ファイル

パスワード保護されたZIPファイルの作成

IronZIPはパスワード保護されたZIPファイルを作成する簡単な方法を提供します。 次のコードサンプルは、ファイルを圧縮し、パスワードを持つ新しいZIPファイルを作成します。

using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Set Password and Encryption Method
            archive.Encrypt("myPa55word", EncryptionMethods.AES256);
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
using System;
using System.IO;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Get all files from the specified directory
        string[] fileArray = Directory.GetFiles(@"D:\Docs\");

        // Create a new ZIP archive
        using (var archive = new IronZipArchive())
        {
            // Iterate through each file and add it to the archive
            foreach (var file in fileArray)
            {
                archive.Add(file); // Add files to the ZIP
            }
            // Set Password and Encryption Method
            archive.Encrypt("myPa55word", EncryptionMethods.AES256);
            // Save the archive to a file
            archive.SaveAs("myZipFile.zip");
        }
    }
}
Imports System
Imports System.IO
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Get all files from the specified directory
		Dim fileArray() As String = Directory.GetFiles("D:\Docs\")

		' Create a new ZIP archive
		Using archive = New IronZipArchive()
			' Iterate through each file and add it to the archive
			For Each file In fileArray
				archive.Add(file) ' Add files to the ZIP
			Next file
			' Set Password and Encryption Method
			archive.Encrypt("myPa55word", EncryptionMethods.AES256)
			' Save the archive to a file
			archive.SaveAs("myZipFile.zip")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

archive.Encrypt("myPa55word", EncryptionMethods.AES256); は、IronZIPを使用してZIPアーカイブにパスワード("myPa55word")を設定します。これにより、AES-256暗号化をアーカイブに適用してセキュリティが強化され、正しいパスワードを持つユーザーのみがコンテンツにアクセスできるようにします。 この機能は、C#アプリケーション内での保管や転送時に機密データを保護するのに有効です。 暗号化アルゴリズムの指定モードを第2パラメータに渡す必要があります。

ファイルは以下のように暗号化されます。

出力

フォルダー内のファイルをC#でZIPする方法: 図2 - 前のコード例から出力された暗号化ファイル

指定されたパスからディレクトリをループしてZIPファイルを作成するデモンストレーションを見てきました。 次に、ファイルの解凍の例に進みましょう。

ZIPアーカイブからファイルを抽出する

IronZIPはC#でZIPアーカイブからファイルを抽出するメソッドを提供します。 次のコードサンプルは、ZIPアーカイブ内の圧縮ファイルを抽出します。

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles");
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles");
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Extract all files from the ZIP archive to the specified directory
		IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles")
	End Sub
End Class
$vbLabelText   $csharpLabel

コード IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles"); は、IronZIPを使用してすべてのファイルを"myZipFile.zip"から抽出し、"myExtractedFiles"ディレクトリに配置します。 この簡潔なメソッドはC#でのZIPアーカイブの抽出プロセスを簡素化し、ファイル抽出タスクのための便利なソリューションを提供します。

出力

出力は次の通りです。

フォルダー内のファイルをC#でZIPする方法: 図3 - 前のコード例から出力されたファイル

パスワード保護されたZIPファイルからの抽出方法

IronZIPはまた、パスワード保護されたZIPファイルを抽出するメソッドを提供します。 次のコードは、指定されたZIPファイルから既存のすべてのファイルとディレクトリを抽出するためにIronZIPメソッドを使用します。

using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the password-protected ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles", "myPa55word");
    }
}
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Extract all files from the password-protected ZIP archive to the specified directory
        IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles", "myPa55word");
    }
}
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Extract all files from the password-protected ZIP archive to the specified directory
		IronZipArchive.ExtractArchiveToDirectory("myZipFile.zip", "myExtractedFiles", "myPa55word")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronZipArchive クラスの ExtractArchiveToDirectory メソッドは、ZIPアーカイブからすべてのエントリを指定されたディレクトリに抽出します。 メソッドに渡す3つの引数:ZIPファイルのパス("myZipFile.zip")、宛先ディレクトリのパス("myExtractedFiles")、ZIPファイルのパスワード("myPa55word")。

この方法で、パスワード保護されたZIPファイルを簡単に抽出できます。

既存のアーカイブにアクセスする方法

IronZIPは、既存のアーカイブにアクセスし、ファイルに存在するすべてのエントリを表示するメソッドを提供します。

using System;
using System.Collections.Generic;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Open an existing ZIP archive with a password
        using (var archive = new IronZipArchive("myZipFile.zip", "myPa55word"))
        {
            // Get entries list
            List<string> names = archive.GetArchiveEntryNames();
            // Iterate through each entry name and print it
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using IronZip;

class Program
{
    static void Main(string[] args)
    {
        // Open an existing ZIP archive with a password
        using (var archive = new IronZipArchive("myZipFile.zip", "myPa55word"))
        {
            // Get entries list
            List<string> names = archive.GetArchiveEntryNames();
            // Iterate through each entry name and print it
            foreach (string name in names)
            {
                Console.WriteLine(name);
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports IronZip

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Open an existing ZIP archive with a password
		Using archive = New IronZipArchive("myZipFile.zip", "myPa55word")
			' Get entries list
			Dim names As List(Of String) = archive.GetArchiveEntryNames()
			' Iterate through each entry name and print it
			For Each name As String In names
				Console.WriteLine(name)
			Next name
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

提供されたC#コードは、IronZIPを使用して、パスワード"myPa55word"で"myZipFile.zip"という名前のZIPファイルをロードすることにより、安全な IronZipArchive インスタンスを作成します。 ファイルが暗号化されていない場合、パスワードパラメータを渡さないでください。 その後、暗号化されたZIPアーカイブ内のエントリ名(ファイル名とフォルダー名)のリストを取得して印刷します。

GetArchiveEntryNames メソッドはエントリ名を収集し、foreach ループが各名前をコンソールに出力します。 この例は、IronZIPがパスワード保護されたZIPアーカイブからエントリ情報を安全にアクセスおよび取得する方法を示しています。

出力

フォルダー内のファイルをC#でZIPする方法: 図4 - 前のコード例からの出力

結論

結論として、IronZIPはZIPファイルを操作するための強力で多用途なC#ライブラリであることが証明されています。 その機能は、基本的な圧縮および抽出を超えて、パスワード保護、暗号化、およびさまざまなアーカイブフォーマットとの互換性を提供します。 バックアップシステムの作成、メール添付ファイルの管理、またはインターネットからのファイルのダウンロードなど、IronZIPはこれらのタスクをシンプルかつ効率的に合理化します。

IronZIPをC#アプリケーションに統合することで、ZIPファイルを扱うための強力なツールを手に入れ、データのセキュリティを強化し、ファイル転送プロセスを最適化できます。 必要に応じて無料のお試しを利用できます。

よくある質問

C#でフォルダーからZIPファイルを作成する方法は?

ディレクトリ内のファイルを反復処理して新しいZIPアーカイブに追加することで、フォルダーからZIPファイルを作成できます。IronZipArchiveクラスを使用し、SaveAsメソッドを呼び出してZIPファイルを保存します。

C# プロジェクトに IronZIP をインストールするにはどうすればよいですか?

Visual StudioのNuGetパッケージマネージャーを使用して、C#プロジェクトにIronZIPをインストールします。パッケージマネージャーコンソールでInstall-Package IronZipコマンドを実行するか、公式IronZIPウェブサイトからダウンロードします。

IronZIPはどのフォーマットをZIPファイル処理にサポートしていますか?

IronZIPは、ZIP、TAR、GZIP、BZIP2などのさまざまなアーカイブフォーマットをサポートしており、さまざまな圧縮およびアーカイブのニーズに対応しています。

C#で作成されたZIPファイルを暗号化できますか?

Yes, you can encrypt ZIP files using IronZIP by applying the Encrypt method with AES-256 encryption to secure your data within the archive.

C#でZIPファイルからファイルを抽出するにはどうすればよいですか?

IronZIPを使用してZIPアーカイブからファイルを抽出するには、ExtractArchiveToDirectoryメソッドを使用し、ソースZIPファイルと宛先ディレクトリを指定します。

C#でパスワード保護されたZIPファイルを扱うことは可能ですか?

はい、IronZIPを使用して、ExtractArchiveToDirectoryなどのメソッドを使用する際にパスワードを提供することで、パスワード保護されたZIPファイルを安全に扱うことができます。

ZIPファイル管理にIronZIPを使用する利点は何ですか?

IronZIPは、暗号化、パスワード保護、複数のアーカイブ形式のサポートなどの機能を提供することで、ファイルのバックアップ、メール添付ファイルの管理、ウェブダウンロードなどのタスクを簡素化します。

IronZIPは.NET 8および他のバージョンをサポートしていますか?

IronZIPは.NET 8、7、6、Core、Standard、Frameworkと互換性があり、さまざまなC#プロジェクトへの統合に柔軟です。

開発者はIronZIPの試用版にどのようにアクセスできますか?

開発者は、IronZIPのウェブサイトのライセンスやダウンロードセクションを訪れてその機能を評価する無料試用版にアクセスできます。

データ転送にZIPファイルを使用する利点は何ですか?

ZIPファイルは、ファイルサイズを削減し、ディスクスペースを節約し、複数のファイルを効率的にインターネットで送信するのを簡素化するため、データ転送に有益です。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。

アイアンサポートチーム

私たちは週5日、24時間オンラインで対応しています。
チャット
メール
電話してね