.NET 環境における SharpZipLib を活用した ZIP 解凍処理の実装

サーバー側で圧縮ファイルのアップロードを扱う場合、受信後の解凍処理が不可欠です。.NET 環境において ZIP 形式のファイルを処理するには、ICSharpCode.SharpZipLib ライブラリの利用が一般的です。このライブラリは NuGet パッケージマネージャーを通じて簡単にプロジェクトへ追加できます。

解凍ロジックをカプセル化するため、共通ユーティリティクラスを作成します。以下の実装では、ストリームの適切な管理とパス結合の安全性を考慮しています。

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;

namespace App.Infrastructure.Compression
{
    public static class ZipUtility
    {
        /// <summary>
        /// ZIP ファイルを指定ディレクトリに解凍します
        /// </summary>
        /// <param name="sourcePath">ZIP ファイルの物理パス</param>
        /// <param name="destinationFolder">解凍先のディレクトリパス</param>
        public static void Decompress(string sourcePath, string destinationFolder)
        {
            if (!Directory.Exists(destinationFolder))
            {
                Directory.CreateDirectory(destinationFolder);
            }

            using (var zipInputStream = new ZipInputStream(File.OpenRead(sourcePath)))
            {
                ZipEntry entry;
                while ((entry = zipInputStream.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(entry.Name);
                    string fileName = Path.GetFileName(entry.Name);

                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        Directory.CreateDirectory(Path.Combine(destinationFolder, directoryName));
                    }

                    if (!string.IsNullOrEmpty(fileName))
                    {
                        string combinedPath = Path.Combine(destinationFolder, entry.Name);
                        using (var streamWriter = File.Create(combinedPath))
                        {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                streamWriter.Write(buffer, 0, bytesRead);
                            }
                        }
                    }
                }
            }
        }
    }
}

作成したユーティリティクラスは、コントローラーなどの上位レイヤーから簡単に呼び出すことができます。ファイルパスの解決を行い、メソッドに渡すことで解凍処理が実行されます。

public ActionResult ExtractArchive()
{
    // 圧縮ファイルの所在パス
    string archivePath = Server.MapPath("~/Uploads/Temp/data.zip");
    
    // 解凍先のディレクトリパス
    string extractPath = Server.MapPath("~/Uploads/Extracted/");

    try
    {
        ZipUtility.Decompress(archivePath, extractPath);
        // 解凍成功後の処理
        return Content("Operation completed successfully");
    }
    catch (Exception ex)
    {
        // エラーハンドリング
        return Content("Error: " + ex.Message);
    }
}

タグ: .NET SharpZipLib C# FileIO compression

8月12日 16:04 投稿