.NET ヘルプ

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

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

SharpZipLibとは何ですか?

SharpZipLibは、完全に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. あなたのVisual Studio IDE C# ConsoleAppで、ソリューションエクスプローラー内のプロジェクトを右クリックし、「NuGet パッケージの管理...」を選択します。

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

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

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

  4. 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
$vbLabelText   $csharpLabel

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

SharpZipLibの制限事項

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

  2. 現代的な機能の欠如:SharpZipLibは最新の.NET機能やプラットフォームをサポートしていないため、現代の開発環境には不向きです。

  3. 限定的なドキュメント:SharpZipLibは長年にわたり存在していますが、そのドキュメントはしばしば不十分で時代遅れであり、開発者が開始したり問題をトラブルシュートするのを難しくしています。

  4. パフォーマンス: SharpZipLibのパフォーマンスは、特に大規模または複雑なアーカイブを扱う際に、開発者の期待を必ずしも満たさない場合があります。

IronZIP:架け橋

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

Sharpziplib ZIP圧縮ファイルの抽出 C# (開発者向けの動作方法): 図 4 - IronZIP for .NET: C# Zipアーカイブライブラリ

IronZIP Features は、SharpZipLib の欠点を補完する堅牢で最新のソリューションとして登場します。 以下の方法でIronZIPがギャップを埋めます:

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

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

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

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

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

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

    IronZIP ドキュメントを参照して、IronZIP の使い始めに関する詳細情報をご覧ください。IronZIP コード例は、手間なく開始するための手助けになります。

IronZIPのインストール

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

  • お使いのVisual Studio IDEまたはお好みのIDEを開いてください。
  • ツールメニューから、NuGetパッケージマネージャーコンソールに移動します。
  • 以下のコマンドを実行してIronZIPパッケージをインストールします:
  Install-Package IronZip
  Install-Package IronZip
SHELL
  • あるいは、NuGet パッケージ マネージャーからインストールすることもできます。
  • NuGet の参照タブから IronZIP を選択し、インストールをクリックします。

    SharpziplibによるZIPファイル抽出 C# (開発者向けの動作方法): 図5 - NuGetパッケージマネージャーの検索バーで「IronZip」と検索し、プロジェクトを選択してインストールボタンをクリックして、Manage NuGet Package for Solutionを使用してIronZIPをインストールします。

コード例

次のソースコードは、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
$vbLabelText   $csharpLabel

出力Zipファイル

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

結論

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

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

IronZIPは無料トライアルライセンスの概要を提供します。 IronZIP ダウンロードからライブラリをダウンロードして試してみてください。

チペゴ
ソフトウェアエンジニア
チペゴは優れた傾聴能力を持ち、それが顧客の問題を理解し、賢明な解決策を提供する助けとなっています。彼は情報技術の学士号を取得後、2023年にIron Softwareチームに加わりました。現在、彼はIronPDFとIronOCRの2つの製品に注力していますが、顧客をサポートする新しい方法を見つけるにつれて、他の製品に関する知識も日々成長しています。Iron Softwareでの協力的な生活を楽しんでおり、さまざまな経験を持つチームメンバーが集まり、効果的で革新的な解決策を提供することに貢献しています。チペゴがデスクを離れているときは、良い本を楽しんだり、サッカーをしていることが多いです。
< 以前
Xceed.Document .NET (開発者向けの動作原理)
次へ >
Xdocument C#(開発者向けの動作方法)