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

C#を使用してフォルダ内のファイルをZIPする方法

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

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

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

IronZipとは何ですか?

IronZIPは、プログラム的にZIPファイルを作成、読み取り、抽出できる強力で多機能なC# ZIPアーカイブライブラリです。 It supports various archive formats, such as ZIP, TAR, GZIP, and BZIP2. また、パスワード保護、暗号化、および圧縮レベルをサポートしています。 IronZIPは.NET 8、7、6、Core、Standard、Frameworkと互換性があります。

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

  1. バックアップシステムの作成: IronZIPを使用して重要なファイルやフォルダーを圧縮して暗号化し、ZIPアーカイブとして安全な場所に保存できます。 この方法でディスクスペースを節約し、不正アクセスからデータを保護することができます。
  2. メールの添付ファイルの送信: IronZIPを使用して添付ファイルをZIPファイルに圧縮することでサイズを減少させ、ファイルサイズ制限を超えないようにし、送信プロセスを迅速化できます。
  3. ウェブからのファイルのダウンロード: IronZIPを使用して、ソフトウェアパッケージ、ドキュメント、画像、その他のファイルを含む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という名前の文字列配列を宣言し、Directory.GetFilesメソッドの結果を割り当て、ディレクトリのパス("D:\Docs")をパラメータとして渡します。 このメソッドは、指定されたディレクトリ内のすべてのファイルの完全な名前を含む文字列の配列を返します。
  • メモリ内にZIPアーカイブを表すIronZipArchiveクラスの新しいインスタンスを作成します。 このインスタンスはarchiveという変数に割り当てられ、usingステートメントでラップされており、コードブロックが終了するとZIPアーカイブが破棄されることを保証します。
  • foreachループを使用してfileArray配列を反復処理し、それぞれのファイルに対して、archiveオブジェクトのAddメソッドを呼び出し、ファイル名をパラメータとして渡します。 このメソッドは、ファイルと同じ名前と内容の新しいエントリをZIPアーカイブに追加します。
  • archiveオブジェクトのSaveAsメソッドを呼び出し、ZIPファイルの名前("myZipFile.zip")をパラメータとして渡します。 このメソッドは、現在のファイルシステムに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#コードは、"myZipFile.zip"という名前のZIPファイルを「myPa55word」というパスワードでロードして安全なIronZipArchiveインスタンスを作成し、IronZIPを使用しています。 ファイルが暗号化されていない場合、パスワードパラメータを渡さないでください。 その後、暗号化されたZIPアーカイブ内のエントリ名(ファイル名とフォルダー名)のリストを取得して印刷します。

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

出力

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

結論

結論として、IronZIPはZIPファイルを操作するための強力で多用途なC#ライブラリであることが証明されています。 Its capabilities extend beyond basic compression and extraction, offering features such as password protection, encryption, and compatibility with various archive formats. バックアップシステムの作成、メール添付ファイルの管理、またはインターネットからのファイルのダウンロードなど、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ファイルを暗号化できますか?

はい、IronZIPを使用してAES-256暗号化を適用し、アーカイブ内のデータを安全にすることでZIPファイルを暗号化できます。

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ボットを作成したりして、技術に対する愛情と創造性を組み合わせています。