.NET ヘルプ

Sharpziplib ZIPファイル抽出 C# (開発者向けの仕組み)

更新済み 6月 6, 2024
共有:

現代のデジタル環境において、データ管理が最優先課題である中、効率的な圧縮・解凍ツールを持つことが重要です。 .NETエコシステムで際立つツールの一つは シャープZipLib. この記事では、SharpZipLibについて詳しく掘り下げ、その機能、用途、そして.NETプロジェクトへの統合方法を探っていきます。

SharpZipLibとは何ですか?

シャープZipLib は、完全にC#で記述された、.NET用の機能豊富なオープンソースの圧縮ライブラリです。 これは、ZIP、GZip、およびTarを含むさまざまな圧縮形式に対する包括的なサポートを提供します。 専念するコミュニティによって開発されたSharpZipLibは、ファイルの圧縮および解凍を効率的に行うための幅広い機能を提供します。

機能と機能

  1. 複数の圧縮フォーマットのサポート: SharpZipLibはZIP、GZip、Tarなどの一般的な圧縮フォーマットをサポートし、さまざまな用途や要件に対応しています。

  2. ストリームベースの操作: このライブラリはストリーム上で動作し、開発者がファイル、メモリストリーム、またはネットワークストリームなどのさまざまなソースからデータを扱うことを可能にします。 この柔軟性により、アプリケーションのさまざまな部分にシームレスに統合することができます。

  3. 圧縮レベル: 開発者は、特定のニーズに基づいて、圧縮率と処理速度のバランスを取るために圧縮レベルを微調整できます。

  4. パスワード保護: SharpZipLib は、指定されたパスワードで内容を暗号化することにより、パスワード保護された ZIP アーカイブの作成を可能にし、データのセキュリティを確保します。

  5. エラーハンドリングとリカバリ: 強力なエラーハンドリングメカニズムは、圧縮および解凍操作中の例外を優雅に処理することを開発者に可能にします。 さらに、SharpZipLibは破損したアーカイブからの復旧をサポートしており、信頼性を向上させます。

ユースケース

  1. ファイル圧縮およびアーカイブ: SharpZipLibは、バックアップユーティリティ、ファイル管理ツール、データエクスポート機能など、ファイルの圧縮およびアーカイブを必要とするアプリケーションに最適です。

  2. WebサービスとAPI: ファイル転送やデータ交換を扱うWebサービスは、帯域幅の使用を減らすために圧縮から利益を得ることが多いです。 SharpZipLibは、送信データを圧縮したり、受信ペイロードを効率的に解凍したりするために、これらのサービスにシームレスに統合できます。

  3. デスクトップアプリケーション: 大規模なデータセットやリソースファイルを扱うデスクトップアプリケーションは、SharpZipLibを活用してファイルを圧縮し、保存や配布に役立てることができます。 これは特にソフトウェアインストーラーやデータ同期ツールに便利です。

  4. データバックアップとストレージ: データの圧縮形式での定期的なバックアップやストレージを必要とするアプリケーションは、SharpZipLib を使用してバックアッププロセスを自動化し、ストレージスペースを効果的に節約することができます。

SharpZipLibの利点

  1. オープンソース: オープンソースライブラリとして、SharpZipLibはコラボレーションとコミュニティの貢献を奨励し、継続的な改良と進化するニーズへの適応を保証します。

  2. クロスプラットフォーム互換性: SharpZipLibはC#で書かれており、.NETフレームワークを対象としているため、Windows、Linux、およびmacOSを含むさまざまなプラットフォームと互換性があり、その汎用性が向上しています。

  3. 軽量かつ効率的: SharpZipLibは軽量で効率的に設計されており、高性能な圧縮および解凍機能を提供しながら、リソース消費を最小限に抑えます。

  4. 充実したドキュメントとサポート: 包括的なドキュメントとコミュニティサポートにより、SharpZipLibを使用する際の統合や問題解決が開発者にとって容易になります。

C# 用 Visual Studio プロジェクトを作成

  1. Visual Studioを開き、「新しいプロジェクトの作成」オプションをクリックします。

  2. 要件に基づいて適切なプロジェクトテンプレートを選択してください (コンソールアプリケーション, Windows フォームアプリケーション).

    SharpziplibのZIPファイル抽出C# (開発者向け): 図1 - 新しいプロジェクトのために、C#の「コンソールアプリ」を選択します。

  3. プロジェクト名と場所を指定し、「次へ」をクリックします。

    Sharpziplib ZIP抽出 C# (開発者向けの仕組み)図2 - プロジェクト名、場所、ソリューション名を指定してプロジェクトを構成します。 次に、.NET Frameworkを選択し、作成をクリックします。

  4. 追加情報から、最新の .NET Framework を選択します。 「作成」をクリックして、プロジェクトを作成します。

インストール手順

.NETプロジェクトにSharpZipLibを統合するには:

  1. ご提供いただいたコンテンツは以下のとおり日本語に翻訳しました:

あなたの ビジュアルスタジオ C# ConsoleApp で、Solution Explorer のプロジェクトを右クリックし、「Manage NuGet Packages...」を選択します。

  1. NuGetパッケージマネージャウィンドウで、「SharpZipLib」を検索してください。

    Sharpziplib ZIPファイル抽出 C#(開発者のための使い方):図3 - NuGetパッケージマネージャの検索バーで「sharpziplib」と検索し、ソリューションのためのManage NuGet Packageを使用してSharpZipLibをインストールします。その後、プロジェクトを選択して、インストールボタンをクリックします。

  2. 検索結果から「SharpZipLib」を選択し、「インストール」ボタンをクリックします。

  3. NuGetは必要な依存関係を自動的にダウンロードしてプロジェクトに追加します。

コード例

SharpZipLibを使用してファイルを圧縮および解凍する方法を示す簡単な例は次のとおりです:

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
namespace SharpZipLibExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceDirectory = @"C:\SourceDirectory";
            string zipFilePath = @"C:\OutputDirectory\compressed.zip";
            // Compress files
            CompressDirectory(sourceDirectory, zipFilePath);
            Console.WriteLine("Files compressed successfully.");
            string extractPath = @"C:\OutputDirectory\extracted";
            // Decompress files
            Decompress(zipFilePath, extractPath);
            Console.WriteLine("Files decompressed successfully.");
        }
        static void CompressDirectory(string sourceDirectory, string zipFilePath)
        {
            using (var zipOutputStream = new ZipOutputStream(File.Create(zipFilePath)))
            {
                zipOutputStream.SetLevel(5); // Compression level (0-9)
                // Recursively add files in the source directory to the ZIP file
                AddDirectoryFilesToZip(sourceDirectory, zipOutputStream);
                zipOutputStream.Finish();
                zipOutputStream.Close();
            }
        }
        static void AddDirectoryFilesToZip(string sourceDirectory, ZipOutputStream zipOutputStream)
        {
            string[] files = Directory.GetFiles(sourceDirectory);
            foreach (string file in files)
            {
                var entry = new ZipEntry(Path.GetFileName(file));
                zipOutputStream.PutNextEntry(entry);
                using (var fileStream = File.OpenRead(file))
                {
                    byte[] buffer = new byte[4096];
                    int sourceBytes;
                    while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zipOutputStream.Write(buffer, 0, sourceBytes);
                    }
                }
            }
            string[] subdirectories = Directory.GetDirectories(sourceDirectory);
            foreach (string subdirectory in subdirectories)
            {
                AddDirectoryFilesToZip(subdirectory, zipOutputStream);
            }
        }
        static void Decompress(string zipFilePath, string extractPath)
        {
            using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry entry;
                while ((entry = zipInputStream.GetNextEntry()) != null)
                {
                    string entryPath = Path.Combine(extractPath, entry.Name);
                    if (entry.IsFile)
                    {
                        string directoryName = Path.GetDirectoryName(entryPath);
                        if (!Directory.Exists(directoryName))
                            Directory.CreateDirectory(directoryName);
                        using (var fileStream = File.Create(entryPath))
                        {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStream.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                    else if (entry.IsDirectory)
                    {
                        Directory.CreateDirectory(entryPath);
                    }
                }
            }
        }
    }
}
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
namespace SharpZipLibExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceDirectory = @"C:\SourceDirectory";
            string zipFilePath = @"C:\OutputDirectory\compressed.zip";
            // Compress files
            CompressDirectory(sourceDirectory, zipFilePath);
            Console.WriteLine("Files compressed successfully.");
            string extractPath = @"C:\OutputDirectory\extracted";
            // Decompress files
            Decompress(zipFilePath, extractPath);
            Console.WriteLine("Files decompressed successfully.");
        }
        static void CompressDirectory(string sourceDirectory, string zipFilePath)
        {
            using (var zipOutputStream = new ZipOutputStream(File.Create(zipFilePath)))
            {
                zipOutputStream.SetLevel(5); // Compression level (0-9)
                // Recursively add files in the source directory to the ZIP file
                AddDirectoryFilesToZip(sourceDirectory, zipOutputStream);
                zipOutputStream.Finish();
                zipOutputStream.Close();
            }
        }
        static void AddDirectoryFilesToZip(string sourceDirectory, ZipOutputStream zipOutputStream)
        {
            string[] files = Directory.GetFiles(sourceDirectory);
            foreach (string file in files)
            {
                var entry = new ZipEntry(Path.GetFileName(file));
                zipOutputStream.PutNextEntry(entry);
                using (var fileStream = File.OpenRead(file))
                {
                    byte[] buffer = new byte[4096];
                    int sourceBytes;
                    while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zipOutputStream.Write(buffer, 0, sourceBytes);
                    }
                }
            }
            string[] subdirectories = Directory.GetDirectories(sourceDirectory);
            foreach (string subdirectory in subdirectories)
            {
                AddDirectoryFilesToZip(subdirectory, zipOutputStream);
            }
        }
        static void Decompress(string zipFilePath, string extractPath)
        {
            using (var zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry entry;
                while ((entry = zipInputStream.GetNextEntry()) != null)
                {
                    string entryPath = Path.Combine(extractPath, entry.Name);
                    if (entry.IsFile)
                    {
                        string directoryName = Path.GetDirectoryName(entryPath);
                        if (!Directory.Exists(directoryName))
                            Directory.CreateDirectory(directoryName);
                        using (var fileStream = File.Create(entryPath))
                        {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStream.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                    else if (entry.IsDirectory)
                    {
                        Directory.CreateDirectory(entryPath);
                    }
                }
            }
        }
    }
}
Imports ICSharpCode.SharpZipLib.Zip
Imports System
Imports System.IO
Namespace SharpZipLibExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim sourceDirectory As String = "C:\SourceDirectory"
			Dim zipFilePath As String = "C:\OutputDirectory\compressed.zip"
			' Compress files
			CompressDirectory(sourceDirectory, zipFilePath)
			Console.WriteLine("Files compressed successfully.")
			Dim extractPath As String = "C:\OutputDirectory\extracted"
			' Decompress files
			Decompress(zipFilePath, extractPath)
			Console.WriteLine("Files decompressed successfully.")
		End Sub
		Private Shared Sub CompressDirectory(ByVal sourceDirectory As String, ByVal zipFilePath As String)
			Using zipOutputStream As New ZipOutputStream(File.Create(zipFilePath))
				zipOutputStream.SetLevel(5) ' Compression level (0-9)
				' Recursively add files in the source directory to the ZIP file
				AddDirectoryFilesToZip(sourceDirectory, zipOutputStream)
				zipOutputStream.Finish()
				zipOutputStream.Close()
			End Using
		End Sub
		Private Shared Sub AddDirectoryFilesToZip(ByVal sourceDirectory As String, ByVal zipOutputStream As ZipOutputStream)
			Dim files() As String = Directory.GetFiles(sourceDirectory)
			For Each file As String In files
				Dim entry = New ZipEntry(Path.GetFileName(file))
				zipOutputStream.PutNextEntry(entry)
				Using fileStream = System.IO.File.OpenRead(file)
					Dim buffer(4095) As Byte
					Dim sourceBytes As Integer
					sourceBytes = fileStream.Read(buffer, 0, buffer.Length)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: while ((sourceBytes = fileStream.Read(buffer, 0, buffer.Length)) > 0)
					Do While sourceBytes > 0
						zipOutputStream.Write(buffer, 0, sourceBytes)
						sourceBytes = fileStream.Read(buffer, 0, buffer.Length)
					Loop
				End Using
			Next file
			Dim subdirectories() As String = Directory.GetDirectories(sourceDirectory)
			For Each subdirectory As String In subdirectories
				AddDirectoryFilesToZip(subdirectory, zipOutputStream)
			Next subdirectory
		End Sub
		Private Shared Sub Decompress(ByVal zipFilePath As String, ByVal extractPath As String)
			Using zipInputStream As New ZipInputStream(File.OpenRead(zipFilePath))
				Dim entry As ZipEntry
				entry = zipInputStream.GetNextEntry()
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: while ((entry = zipInputStream.GetNextEntry()) != null)
				Do While entry IsNot Nothing
					Dim entryPath As String = Path.Combine(extractPath, entry.Name)
					If entry.IsFile Then
						Dim directoryName As String = Path.GetDirectoryName(entryPath)
						If Not Directory.Exists(directoryName) Then
							Directory.CreateDirectory(directoryName)
						End If
						Using fileStream = File.Create(entryPath)
							Dim buffer(4095) As Byte
							Dim bytesRead As Integer
							bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
							Do While bytesRead > 0
								fileStream.Write(buffer, 0, bytesRead)
								bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)
							Loop
						End Using
					ElseIf entry.IsDirectory Then
						Directory.CreateDirectory(entryPath)
					End If
					entry = zipInputStream.GetNextEntry()
				Loop
			End Using
		End Sub
	End Class
End Namespace
VB   C#

SharpZipLibは、長年.NET言語開発コミュニティにおいて不可欠な機能を提供しており、ZIP、GZip、Tar、BZip2などの圧縮アーカイブの操作において重要な役割を果たしてきました。しかし、技術が進化し、開発者がより高度なソリューションを求める中で、SharpZipLibのいくつかの制限が明らかになってきています。

SharpZipLibの制限事項

  1. 複雑さ: SharpZipLibのAPIは扱いにくく冗長で、ZIPアーカイブの作成や抽出などの簡単なタスクを実行するために、開発者が長いコードを書く必要があります。

  2. 最新機能の欠如:SharpZipLibは最新の.NET機能およびプラットフォームをサポートしておらず、現代の開発環境にはあまり適していません。

  3. 限定的なドキュメント: SharpZipLibは長い間存在していますが、そのドキュメントはしばしば断片的で古く、開発者が始めたり問題解決を行うのが難しいことがあります。

  4. パフォーマンス: SharpZipLibのパフォーマンスは、特に大規模または複雑なアーカイブを扱う場合、開発者の期待に応えられないことがあります。

IronZIP:架け橋

IronZIPによって開発された アイアンソフトウェアは、.NET アプリケーション内で ZIP アーカイブを管理するための最新かつ効率的なソリューションです。 直感的なAPIを使用して、開発者は簡単にZIPファイルを作成、読み取り、および操作できます。 IronZIPは、カスタマイズ可能な圧縮レベルやパスワード保護などの高度な機能を提供し、柔軟性とデータセキュリティを確保します。 最新の.NETバージョンと互換性があり、パフォーマンスの最適化がされているIronZIPは、アーカイブ管理タスクを容易かつ効率的に簡素化します。

シャープジップリブ ZIP 解凍 C#(開発者のための動作説明):図4 - IronZIP for .NET:C# Zip アーカイブ ライブラリ

IronZIP SharpZipLibの欠点を解消する強力で最新のソリューションとして登場します。 以下の方法でIronZIPがギャップを埋めます:

  1. 高度なAPI: IronZIPは、アーカイブ管理タスクを簡素化する直感的で開発者に優しいAPIを提供します。 IronZIPを使用すると、開発者はほんの数行のコードで複雑な操作を実行でき、開発時間と労力を削減できます。

  2. フル.NETサポート: IronZIPは、最新の.NETバージョン、.NET Core、.NET Standard、.NET Frameworkを完全にサポートしており、最新の開発環境とプラットフォームとの互換性を確保します。

  3. 包括的なドキュメント:IronZIPは包括的なドキュメントと例を提供しており、開発者がその機能と能力を迅速に把握できるように支援します。 広範なドキュメントは学習曲線をスムーズにし、プロジェクトへの迅速な統合を促進します。

  4. 圧縮レベル制御: IronZIPは、開発者に圧縮レベルの制御を提供し、要求に応じて圧縮レベルを調整できるようにします。 この機能により、開発者はファイルサイズの削減と圧縮速度のバランスを取ることができます。

  5. パスワード保護:IronZIPはZIPアーカイブのパスワード保護に対応しており、機密データのセキュリティを強化します。 開発者は従来のパスワード、AES128、およびAES256パスワードを使用してZIPアーカイブを簡単に暗号化でき、許可されたユーザーのみがアーカイブの内容にアクセスできるようにします。

  6. パフォーマンス最適化: IronZIPはパフォーマンスのために最適化されており、SharpZipLibと比較してより高速な圧縮および抽出速度を提供します。 この最適化により、開発者はパフォーマンスを損なうことなく、大量のデータを効率的に処理することができます。

    また、以下を提供します ドキュメント IronZIPの始め方に関するページ。すぐに使用できる コード例 簡単に始めることができます。

IronZIPのインストール

IronPDFとXDocumentを統合する手順は次のとおりです:

  • 開く ビジュアルスタジオ もしくはお好みのIDE。
  • ツールメニューから、NuGetパッケージマネージャーコンソールに移動します。

  • 以下のコマンドを実行してIronZIPパッケージをインストールします:
  :ProductInstall
  • あるいは、NuGet パッケージ マネージャーからインストールすることもできます。
  • NuGet の参照タブから IronZIP を選択し、インストールをクリックします。

    Sharpziplib Extract ZIP C#(開発者向けの動作方法):図5 - NuGet パッケージマネージャの検索バーで「IronZIP」を検索し、[ソリューション用の NuGet パッケージを管理] を使用して IronZIP をインストールします。その後、プロジェクトを選択し、[インストール]ボタンをクリックしてください。

コード例

以下のソースコードは、IronZIPがいかに効率的であるかを示しています。 ZIPファイルを作成します 簡単に数行のコードで。 こちらで複数のファイルを追加できます: パスワード保護されたZIP 指定されたフォルダー内のファイル名を提供することで、アーカイブを作成します。 IronZipArchive オブジェクトを作成するとき、出力ファイルのスペースサイズを減らすために圧縮レベルを指定することもできます。

using IronZip;
using IronZip.Enum;
class Program
{
    static void Main()
    {
        // Create an empty ZIP with the highest compression
        using (var archive = new IronZipArchive(9))
        {
            // Password protect the ZIP (Support AES128 & AES256)
            archive.SetPassword("P@ssw0rd", EncryptionMethods.Traditional);
            archive.AddArchiveEntry("./assets/file1.txt");
            archive.AddArchiveEntry("./assets/file2.txt");
            // Export the ZIP
            archive.SaveAs("output.zip");
        }
    }
}
using IronZip;
using IronZip.Enum;
class Program
{
    static void Main()
    {
        // Create an empty ZIP with the highest compression
        using (var archive = new IronZipArchive(9))
        {
            // Password protect the ZIP (Support AES128 & AES256)
            archive.SetPassword("P@ssw0rd", EncryptionMethods.Traditional);
            archive.AddArchiveEntry("./assets/file1.txt");
            archive.AddArchiveEntry("./assets/file2.txt");
            // Export the ZIP
            archive.SaveAs("output.zip");
        }
    }
}
Imports IronZip
Imports IronZip.Enum
Friend Class Program
	Shared Sub Main()
		' Create an empty ZIP with the highest compression
		Using archive = New IronZipArchive(9)
			' Password protect the ZIP (Support AES128 & AES256)
			archive.SetPassword("P@ssw0rd", EncryptionMethods.Traditional)
			archive.AddArchiveEntry("./assets/file1.txt")
			archive.AddArchiveEntry("./assets/file2.txt")
			' Export the ZIP
			archive.SaveAs("output.zip")
		End Using
	End Sub
End Class
VB   C#

出力Zipファイル

Sharpziplib ZIP抽出 C#(開発者向けの仕組み):図6 - 出力:IronZIPを使用して作成されたパスワード保護付きのZipアーカイブ。

結論

シャープZipLib .NET用の強力な圧縮ライブラリとして登場し、圧縮ファイルを効率的に処理するための豊富な機能と能力を提供します。 データの保存、ファイルのアーカイブ、またはウェブサービスでの帯域幅の最適化など、SharpZipLibは圧縮と解凍の操作を効率化するために必要なツールを提供します。 オープンソースの性質、クロスプラットフォーム互換性、および堅牢な機能性を備えているため、SharpZipLibは.NETアプリケーションで圧縮タスクの信頼できるソリューションを求める開発者にとって、依然としてトップの選択肢です。

SharpZipLibは、.NETアプリケーションで圧縮アーカイブを扱うための信頼できる選択肢であり続けていますが、現在の開発環境においてその限界がますます明らかになっています。 IronZIP SharpZipLibが残したギャップを埋めるために、使いやすさ、パフォーマンス、互換性を重視した現代的で機能豊富な代替手段を提供します。 IronZIPを使用すると、開発者はアーカイブ管理における新しい可能性を解放し、高度な機能と直感的な操作性で開発ワークフローを効率化することができます。 API.

IronZIPは、 無料試用 ページ ライブラリを以下からダウンロード これ リンクをクリックしてお試しください。

< 以前
Xceed.Document .NET (開発者向けの動作原理)
次へ >
Xdocument C#(開発者向けの動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >