C#のメモリにZIPファイルを作成する方法

このステップバイステップのチュートリアルでは、C#のメモリにZIPファイルを作成する方法を学習します。メモリ内にZIPアーカイブを作成できるようにするには、次の簡単な手順を実行する必要があります。

C#のメモリにZIPファイルを作成する手順

1.Aspose.ZIP for .NETNuGetパッケージ参照をソリューションに追加します 2.Program.csコードファイルにAspose.Zipステートメントを使用して追加します 3.License.SetLicenseメソッドを使用してAspose.ZIPAPIのライセンスを適用します 4.ディスク上にあるフォルダから単一またはすべてのファイルを取得し、それらのパスを文字列配列に保存します 5.メモリにArchive Classのオブジェクトを作成します 6.ファイルごとに、ZIPアーカイブにArchiveEntryノードを作成します 7.ZIPアーカイブインスタンスをMemoryStreamに保存またはコピーします

次のC#コード例を.NETアプリケーションで使用して、ディスク上のフォルダー内のすべてのファイルをZIP file formatに圧縮し、ZIPファイルをメモリストリームオブジェクトに保存できます。

C#のメモリにZIPファイルを作成するコード

using System.IO;
// Following namespace is required to Create ZIP File in Memory
using Aspose.Zip;
namespace CreateZipFileInMemory
{
class Program
{
static void Main(string[] args)
{
License AsposeZipLicense = new License();
// Load license from file system into memory stream
using (MemoryStream stream = new MemoryStream(File.ReadAllBytes("path to license.lic")))
{
// Set license prior to creating ZIP file in memory
AsposeZipLicense.SetLicense(stream);
}
#region C# code to create ZIP archive in memory
// Create MemoryStream instance
using (MemoryStream zipFileInMemory = new MemoryStream())
{
// Create empty Archive object for ZIP file
using (Aspose.Zip.Archive zipArchive = new Aspose.Zip.Archive())
{
// Get all files from a Folder and store their paths in string Array
string[] filesArray = Directory.GetFiles("ZIP all Files\\", "*.*", SearchOption.TopDirectoryOnly);
// Loop through the Array and create an ArchiveEntry against each file within the ZIP Archive
foreach (string fileDiskPath in filesArray)
{
string[] folders = fileDiskPath.Split(new char[] { '\\' });
string fileName = folders[folders.Length - 1];
zipArchive.CreateEntry(fileName, fileDiskPath);
}
// Call Save method to create ZIP Archive in memory
zipArchive.Save(zipFileInMemory);
}
}
#endregion
}
}
}

したがって、このC#のメモリコンソールアプリケーションでのzipファイルの作成は、基本的に、フォルダをZIP形式に変換し、フォルダのコンテンツ全体を圧縮形式でメモリに書き込むのに役立ちます。その後、MemoryStream C#からZIPファイルを再作成し、ディスクに保存できます。アーカイブがファイルシステム上に再作成されると、C#を使用してZIPファイルを抽出するコードを作成できます。

 日本語