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

C#でZIPファイルを開く方法

ZIPは、可逆圧縮をサポートするアーカイブファイルシステムフォーマットです。 ZIPファイルには、圧縮された1つ以上のファイルやディレクトリが含まれる場合があります。 ZIPファイル形式では複数の圧縮アルゴリズムが許可されていますが、DEFLATEが最も一般的です。 ZIP形式は、多くのソフトウェアユーティリティで迅速にサポートされました。 主要なOSプロバイダーは、長い間ZIPアーカイブのサポートを提供しています。マイクロソフトはWindows 98以降、ZIPファイルのサポートを含めました。

このブログでは、IronZIPを使用してZIPアーカイブファイルや抽出されたファイルを開くための、現代的で簡単かつ効率的な方法を探ります。 ZIPファイルの一般的な情報とその利点について学びます。 その後、ZIPファイル形式を操作するためのシステムネームスペース内で利用可能なオプションを確認します。 次に、ZIPファイルを開き、ZIPファイルを一時フォルダに解凍し、新しいZIPファイルを作成し、既存のZIPファイルにファイルを追加するステップバイステップの手順を探ります。

ソフトウェアアプリケーションでZIPファイルを使用する利点

  1. 圧縮: Implode、Deflate、Deflate64、bzip2、LZMA、WavPack、PPMdなどのさまざまな圧縮アルゴリズムを使用して、アーカイブされたファイル/フォルダのサイズを縮小します。
  2. 転送時間の短縮: ファイルサイズが小さいと、特にインターネットを介してファイルを送信する際に転送時間が速くなります。 これは、メールの添付ファイルやウェブサイトからのファイルのアップロードやダウンロードに特に有利です。
  3. ファイルの統合: ZIPファイルを使用すると、複数のファイルを1つのアーカイブに統合でき、管理するファイルの数を減らすことができます。 これは、複数のファイルから成るソフトウェアを整理したり配布したりするのに便利です。
  4. パスワード保護: 多くのZIPユーティリティは、アーカイブをパスワードで保護するオプションを提供し、ファイルへのセキュリティレイヤーを追加します。 これはZIPファイルの内容へのアクセスを制限したい場合に便利です。

IronZIPを使用してZIPアーカイブを作成し、ZIPファイルを抽出する

IronZIPライブラリとドキュメントの紹介はこちらで見つけることができます。 C#アプリケーションでは、ZIPファイルをさまざまな方法で作成および抽出できます。 IronZIP NuGetパッケージには、ZIP、TAR、GZIP、BZIP2などの異なる形式でファイルをアーカイブするためのすべての機能が含まれています。以下は、IronZIPを使用して最新のアプリケーションプログラミングで次世代アプリを構築し、ZIPファイルを開く、ZIPファイルを抽出する、新しいZIPファイルを作成するなどのサンプルステップです。

ステップ1. .NET Coreコンソールアプリケーションの作成

プロジェクトを作成する

Visual Studioを使用して.NETコンソールアプリを作成できます。 Visual Studioを開いて、プロジェクトの作成を選択してください。 ここでは、プロジェクトを作成するさまざまなテンプレートを見ることができます。 コードをデモまたはテストする最も簡単な方法は、コンソールアプリケーションを作成することです。 コンソールアプリプロジェクトテンプレートを選択します。

C#でZipファイルを開く方法: 図1 - 新しいプロジェクト

プロジェクト名を入力する

以下のウィンドウで、プロジェクト名、ファイルシステムに保存するプロジェクトの場所、最後にソリューションフォルダーへのパスを入力できます。 ソリューションとプロジェクトフォルダーを同じにするか、異なるフォルダーにすることができます。

C#でZipファイルを開く方法: 図2 - プロジェクトの構成

.NETフレームワークのバージョンを選択する

次のステップは、プロジェクトの.NETフレームワークのバージョンを選択します。 特定のバージョンで開発したい場合、そのバージョンを指定してください。そうでなければ、常に最新の安定版を選択してプロジェクトを作成します。 最新バージョンはMicrosoftのウェブサイトからダウンロードできます。その後、作成をクリックしてコンソールアプリケーションを生成します。

C#でZipファイルを開く方法: 図3 - ターゲットフレームワーク

これにより、テンプレートからデフォルトのプロジェクトが作成され、指定されたディレクトリにプロジェクトとソリューションファイルが保存されます。 プロジェクトが作成されると、以下のようになります。 最新バージョンではprogram.csでクラスが使用されないことがあります。

// Import necessary namespaces
using System;

// Define the namespace
namespace MyApp // Note: actual namespace depends on the project name.
{
    // Define the Program class
    internal class Program
    {
        // Main method: Entry point of the application
        static void Main(string[] args)
        {
            // Print a welcome message
            Console.WriteLine("Hello, World!");
        }
    }
}
// Import necessary namespaces
using System;

// Define the namespace
namespace MyApp // Note: actual namespace depends on the project name.
{
    // Define the Program class
    internal class Program
    {
        // Main method: Entry point of the application
        static void Main(string[] args)
        {
            // Print a welcome message
            Console.WriteLine("Hello, World!");
        }
    }
}
' Import necessary namespaces
Imports System

' Define the namespace
Namespace MyApp ' Note: actual namespace depends on the project name.
	' Define the Program class
	Friend Class Program
		' Main method: Entry point of the application
		Shared Sub Main(ByVal args() As String)
			' Print a welcome message
			Console.WriteLine("Hello, World!")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

新しいZIPファイルを作成し、すべてのZIPアーカイブファイルを抽出するために、デフォルトライブラリのSystem.IO.Compressionを使用できます。 以下のコードは、ZipFile.OpenReadおよびZipFile.Openの静的メソッドを使用して、ZIPファイルを開いたりZIPファイルを抽出したりする方法を示しています。

// Import necessary namespaces
using System;
using System.IO;
using System.IO.Compression;

public class ZipExample
{
    public static void Main()
    {
        Console.WriteLine("-----------Zip - Unzip-----------");

        // Method to add a file entry to the ZIP archive
        static void AddEntry(string filePath, ZipArchive zipArchive)
        {
            // Get file name from the file path
            var file = Path.GetFileName(filePath);

            // Create a new entry in the ZIP archive for the file
            zipArchive.CreateEntryFromFile(filePath, file);
        }

        // Name of the ZIP file to be created
        var zip = "myFile.zip";

        // Open or create the ZIP file for updating
        using (ZipArchive archive = ZipFile.Open(zip, ZipArchiveMode.Update))
        {
            // Add files to the archive
            AddEntry("file1.txt", archive);
            AddEntry("file2.txt", archive);
        }

        // Directory where we want to extract the ZIP files
        var dirToExtract = "extract";

        // Create the directory if it does not exist
        if (!Directory.Exists(dirToExtract))
        {
            Directory.CreateDirectory(dirToExtract);
        }

        // Extract the contents of the ZIP file to the specified directory
        ZipFile.ExtractToDirectory(zip, dirToExtract);

        // Indicate that extraction is complete
        Console.WriteLine("Files extracted to: " + dirToExtract);
    }
}
// Import necessary namespaces
using System;
using System.IO;
using System.IO.Compression;

public class ZipExample
{
    public static void Main()
    {
        Console.WriteLine("-----------Zip - Unzip-----------");

        // Method to add a file entry to the ZIP archive
        static void AddEntry(string filePath, ZipArchive zipArchive)
        {
            // Get file name from the file path
            var file = Path.GetFileName(filePath);

            // Create a new entry in the ZIP archive for the file
            zipArchive.CreateEntryFromFile(filePath, file);
        }

        // Name of the ZIP file to be created
        var zip = "myFile.zip";

        // Open or create the ZIP file for updating
        using (ZipArchive archive = ZipFile.Open(zip, ZipArchiveMode.Update))
        {
            // Add files to the archive
            AddEntry("file1.txt", archive);
            AddEntry("file2.txt", archive);
        }

        // Directory where we want to extract the ZIP files
        var dirToExtract = "extract";

        // Create the directory if it does not exist
        if (!Directory.Exists(dirToExtract))
        {
            Directory.CreateDirectory(dirToExtract);
        }

        // Extract the contents of the ZIP file to the specified directory
        ZipFile.ExtractToDirectory(zip, dirToExtract);

        // Indicate that extraction is complete
        Console.WriteLine("Files extracted to: " + dirToExtract);
    }
}
' Import necessary namespaces
Imports System
Imports System.IO
Imports System.IO.Compression

Public Class ZipExample
	Public Shared Sub Main()
		Console.WriteLine("-----------Zip - Unzip-----------")

		' Method to add a file entry to the ZIP archive
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'		static void AddEntry(string filePath, ZipArchive zipArchive)
'		{
'			' Get file name from the file path
'			var file = Path.GetFileName(filePath);
'
'			' Create a new entry in the ZIP archive for the file
'			zipArchive.CreateEntryFromFile(filePath, file);
'		}

		' Name of the ZIP file to be created
		Dim zip = "myFile.zip"

		' Open or create the ZIP file for updating
		Using archive As ZipArchive = ZipFile.Open(zip, ZipArchiveMode.Update)
			' Add files to the archive
			AddEntry("file1.txt", archive)
			AddEntry("file2.txt", archive)
		End Using

		' Directory where we want to extract the ZIP files
		Dim dirToExtract = "extract"

		' Create the directory if it does not exist
		If Not Directory.Exists(dirToExtract) Then
			Directory.CreateDirectory(dirToExtract)
		End If

		' Extract the contents of the ZIP file to the specified directory
		ZipFile.ExtractToDirectory(zip, dirToExtract)

		' Indicate that extraction is complete
		Console.WriteLine("Files extracted to: " & dirToExtract)
	End Sub
End Class
$vbLabelText   $csharpLabel

上記のコードではmyFile.zipという名前のZIPファイルがシステムネームスペースを使用して使われています。 Openメソッドは、指定されたモードでZIPファイルを開くために使用されます。 これも新しいZIPアーカイブファイルを作成するために使用できます。 開いた後、メソッドAddEntryを使用して新しいアーカイブエントリを追加し、ExtractToDirectoryはZIPアーカイブファイルを指定されたディレクトリに抽出します。 ディレクトリが存在しない場合、Directory.CreateDirectoryを使用して作成されます。

ステップ2. NuGetパッケージマネージャーを使用したIronZIPのインストール

Visual Studioからプロジェクトマネージャーを開き、IronZIPパッケージを検索します。 次に最新バージョンを選択してインストールをクリックします。 ドロップダウンからインストールするバージョンを変更できます。 その後、インストールをクリックします。

C#でZipファイルを開く方法: 図4 - NuGetパッケージマネージャー

IronZIPを使用してZIPアーカイブファイルを作成し、ファイルを追加する

C#でZipファイルを開く方法: 図5 - IronZIP

IronZIP is an archive compression and decompression library developed by Iron Softwareによって開発されたアーカイブ圧縮と解凍のライブラリです。 広く使用されているZIP形式に加えて、TAR、GZIP、BZIP2にも対応しています。

IronZIPは、正確性、使いやすさ、速度を重視したC# ZIPアーカイブライブラリです。 その使いやすいAPIにより、開発者は数分で現代の.NETプロジェクトにアーカイブ機能を簡単に追加できます。

IronZIPは、System.IO.Compressionライブラリと比較して多くの利点を提供します。 圧縮時に希望する圧縮比率を指定し、ZIP、TAR、GZIP、BZIP2などの異なる圧縮アルゴリズムを使用することもできます。また、モバイル、ウェブ、デスクトッププラットフォームおよびさまざまな.NETバージョンをサポートしています。

// Setup: Specify the path for the new ZIP archive
var archivePath = "ironZip.zip";

// Check if the archive already exists, and delete it if so
if (File.Exists(archivePath))
{
    File.Delete(archivePath);
}

// Use IronZIP library to create a new ZIP archive
using (var archive = new IronZipArchive(9)) // Compression level: 9 for maximum compression
{
    // Add files to the ZIP archive
    archive.Add("file1.txt");
    archive.Add("file2.txt");

    // Save the archive to the specified path
    archive.SaveAs(archivePath);
}
// Setup: Specify the path for the new ZIP archive
var archivePath = "ironZip.zip";

// Check if the archive already exists, and delete it if so
if (File.Exists(archivePath))
{
    File.Delete(archivePath);
}

// Use IronZIP library to create a new ZIP archive
using (var archive = new IronZipArchive(9)) // Compression level: 9 for maximum compression
{
    // Add files to the ZIP archive
    archive.Add("file1.txt");
    archive.Add("file2.txt");

    // Save the archive to the specified path
    archive.SaveAs(archivePath);
}
' Setup: Specify the path for the new ZIP archive
Dim archivePath = "ironZip.zip"

' Check if the archive already exists, and delete it if so
If File.Exists(archivePath) Then
	File.Delete(archivePath)
End If

' Use IronZIP library to create a new ZIP archive
Using archive = New IronZipArchive(9) ' Compression level: 9 for maximum compression
	' Add files to the ZIP archive
	archive.Add("file1.txt")
	archive.Add("file2.txt")

	' Save the archive to the specified path
	archive.SaveAs(archivePath)
End Using
$vbLabelText   $csharpLabel

初期ソースコードは、ZIPアーカイブファイル名を指定し、指定されたディレクトリが存在するかどうかを確認することで設定されます。 その後、Addメソッドを使用してファイルをアーカイブしてZIPファイルを作成します。 圧縮パラメータの2番目のパラメータは、低い圧縮では1、高い圧縮では9です。 テキストファイルは9を使用して損失なしで最大限に圧縮でき、画像ファイルはデータ損失を避けるために低い圧縮を使用できます。

IronZIPを使用してZIPアーカイブファイルを開く

IronArchiveクラスも、ZIPアーカイブファイルからファイルを抽出するために使用できます。すべてファイルはIronArchive.ExtractArchiveToDirectoryを使用して抽出され、以下のように特定のディレクトリにファイルを抽出するのに役立ちます。

// Directory to extract all files from the ZIP archive
var extractionPath = "IronZipFiles";

// Check if the directory exists; if not, create it
if (!Directory.Exists(extractionPath))
{
    Directory.CreateDirectory(extractionPath);
}

// Extract all files from the specified ZIP archive to the directory
IronArchive.ExtractArchiveToDirectory("ironZip.zip", extractionPath);
// Directory to extract all files from the ZIP archive
var extractionPath = "IronZipFiles";

// Check if the directory exists; if not, create it
if (!Directory.Exists(extractionPath))
{
    Directory.CreateDirectory(extractionPath);
}

// Extract all files from the specified ZIP archive to the directory
IronArchive.ExtractArchiveToDirectory("ironZip.zip", extractionPath);
' Directory to extract all files from the ZIP archive
Dim extractionPath = "IronZipFiles"

' Check if the directory exists; if not, create it
If Not Directory.Exists(extractionPath) Then
	Directory.CreateDirectory(extractionPath)
End If

' Extract all files from the specified ZIP archive to the directory
IronArchive.ExtractArchiveToDirectory("ironZip.zip", extractionPath)
$vbLabelText   $csharpLabel

上記のコードはZIPファイルをディレクトリに抽出します。 コードはディレクトリが存在するかどうかをチェックし、存在しない場合はZIPアーカイブファイルが指定されたディレクトリに抽出されます。

ライセンス (無料トライアル利用可能)

上記のコードを機能させるには、ライセンスキーが必要です。 このキーは appsettings.json に配置する必要があります。

{
    "IronZip.LicenseKey": "your license key"
}

開発者向けにこちらで登録すると、試用ライセンスが提供され、はい、試用ライセンスにはクレジットカードは必要ありません。 メールIDを入力して無料トライアルに登録できます。

既存のZIPアーカイブファイルにファイルを追加する

既存のアーカイブを開くために、IronZIPからの静的FromFileメソッドを使用します。このメソッドは出力として作成される新しいアーカイブのファイル名を指定することも必要です。

// Path to a new file to be added to the existing ZIP archive
const string file3 = ".\\image3.png";
var archivePlusPath = "ironZipPlus.zip";

// Open the existing ZIP archive and add a new file
using (var file = IronArchive.FromFile("ironZip.zip", archivePlusPath))
{
    // Add additional files to the existing archive
    file.Add(file3);
}
// Path to a new file to be added to the existing ZIP archive
const string file3 = ".\\image3.png";
var archivePlusPath = "ironZipPlus.zip";

// Open the existing ZIP archive and add a new file
using (var file = IronArchive.FromFile("ironZip.zip", archivePlusPath))
{
    // Add additional files to the existing archive
    file.Add(file3);
}
' Path to a new file to be added to the existing ZIP archive
Const file3 As String = ".\image3.png"
Dim archivePlusPath = "ironZipPlus.zip"

' Open the existing ZIP archive and add a new file
Using file = IronArchive.FromFile("ironZip.zip", archivePlusPath)
	' Add additional files to the existing archive
	file.Add(file3)
End Using
$vbLabelText   $csharpLabel

コードは静的メソッドIronArchive.FromFileを利用して既存のZIPファイルを開き、新しいファイルをアーカイブエントリとして追加します。 ファイルオブジェクトが破棄されると、更新されたアーカイブが正常に保存されます。

更新

IronZIPライブラリは顧客/ユーザーからのフィードバックに基づいて継続的に更新されており、すべての更新をこちらで確認できます。

結論

結論として、ZIPファイルプログラミングは現在のアプリケーション開発において重要なスキルであり、クラウドホストプロバイダーによってストレージおよびデータ転送コストが課される中で構築されます。 このスキルを知っていることは、プログラマーがアプリケーションのコストを削減し、アプリケーションのパフォーマンスを向上させるのに役立ちます。

インストール手順に従い、提供されたコード例を探ることで、開発者は迅速にIronZIPの力を活用してZIPタスクを簡単に処理できます。 ますます多くのアプリケーションが近代化され、クラウドに移行されるにつれて、IronZIPのような信頼できるZIPライブラリは、C#開発者が最新のアプリケーション開発の要求を満たすために必要なツールを提供します。 したがって、IronZIPの力を受け入れ、C#アプリケーションでZIPファイルを操作するための新しい可能性を開放してください。

IronZIPはその開発者に広範なサポートを提供します。 C#用IronZIPの動作について知るには、こちらをご覧ください。 IronZIP offers a free trial license which is a great opportunity to know IronZIPとその機能を知るための素晴らしい機会です。

Iron Softwareは他のさまざまなライブラリを持っており、それらを探索して知識を深め、最新のアプリケーションをプログラム/開発するためのスキルを更新してください。

よくある質問

C#でZIPファイルを開くにはどうすればよいですか?

C#ではSystem.IO.Compression ライブラリを使用して ZIPファイルを開くことができます。代わりに、IronZIP ではZIPファイルの処理に対して高度な機能を提供し、アーカイブ管理のためのより簡単で効率的な方法を提供します。

C#でZIPアーカイブからファイルを抽出する方法は?

IronZIPを使用すると、IronArchive.ExtractArchiveToDirectory メソッドを使用して ZIP アーカイブからファイルを抽出できます。このメソッドでは、ZIP ファイルと抽出先のディレクトリを指定する必要があります。

アプリケーション開発に ZIP ファイルを使用する利点とは?

ZIP ファイルはファイルサイズを縮小し、転送時間を短縮し、複数のファイルを1つのアーカイブにまとめることができます。IronZIP は圧縮比の指定、複数の形式のサポートなどの追加機能でこれらの利点を強化します。

C#で既存のZIPアーカイブにファイルを追加するにはどうすればよいですか?

IronZIPを使用して既存のZIPアーカイブにファイルを追加するには、IronArchive.FromFileメソッドを使用してアーカイブを開き、その後Addメソッドを使用して新しいファイルを追加します。プロセスを完了するには、更新したアーカイブを保存します。

IronZIPを使用して新しいZIPファイルを作成し、ファイルを追加することはできますか?

はい、IronZIPを使用すると、アーカイブのパスを指定して新しいZIPファイルを作成し、Addメソッドを使用してファイルを追加できます。その後、SaveAsメソッドを使用してアーカイブを保存します。

NuGet パッケージ マネージャーを使用して IronZIP をインストールするにはどうすればよいですか?

NuGet パッケージ マネージャー経由で IronZIP をインストールするには、Visual Studio のプロジェクト マネージャーを開いて IronZIP を検索し、最新バージョンを選んでインストールをクリックします。これにより、IronZIP がプロジェクトに追加され、ZIP ファイルの管理が可能になります。

IronZIP は複数の圧縮フォーマットをサポートしていますか?

はい、IronZIP は ZIP、TAR、GZIP、BZIP2 などの複数の圧縮フォーマットをサポートしており、さまざまなアプリケーションニーズに柔軟に対応します。

IronZIP の無料トライアルはありますか?

はい、IronZIP は開発者向けに無料のトライアルを提供しています。Iron Software のウェブサイトで登録することで、クレジットカード不要でアクセスできます。

IronZIPが現代のアプリケーション開発に最適な選択肢である理由は何ですか?

IronZIP はその使いやすさ、速度、クロスプラットフォームの互換性で知られており、これらの機能により、現代のアプリケーション開発に理想的な選択肢となっています。

Curtis Chau
テクニカルライター

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

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