yotiky Tech Blog

とあるエンジニアの備忘録

Azure Functions で アップロードした ZIP ファイルの中身を列挙する

目次

検証環境

  • Azure Functions v3

実装

using System.IO.Compression;
foreach (var file in form.Files)
{
    using (var stream = file.OpenReadStream())
    using (var zip = new ZipArchive(stream, ZipArchiveMode.Read, true))
    {
        foreach (var entry in zip.Entries)
        {
            log.LogInformation(entry.FullName);
        }
    }
}

実行結果は以下の通り。

[2021-03-08T11:50:37.540Z] ParentDir/Memo1.txt
[2021-03-08T11:50:37.542Z] ParentDir/SubDir/SubDirMemo1.txt
[2021-03-08T11:50:37.542Z] ParentDir/SubDir/SubDirMemo2.txt

エンコード

zip ファイル内に日本語のフォルダまたはファイルが含まれる場合は注意が必要。 一般的に Windows 環境で圧縮した場合は Shift-JIS が使用され、Unix 系や Mac などで圧縮した場合は UTF-8 が使用される。

.NET Core で、Shift-JIS を使用する場合、NuGetで System.Text.Encoding.CodePages をインストールする必要がある。

また、Azure Functions の SDK では、Function Runtime が持っているアセンブリを除外するため、そのままだと例外が発生して動かない。 Azure Functions で上記パッケージを使う場合は csproj に以下の設定を追加する。

<PropertyGroup>
    <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
</PropertyGroup>

ZipArchive のコンストラクタでエンコードを指定する。

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

using (var stream = file.OpenReadStream())
using (var zip = new ZipArchive(stream, ZipArchiveMode.Read, true, Encoding.GetEncoding("Shift_JIS")))
{
}

yotiky.hatenablog.com

参考