LoginSignup
1
0

More than 5 years have passed since last update.

.NET Framework で ZipArchive.CreateEntryFromFile メソッドにうまくアクセスできないとき

Last updated at Posted at 2017-08-21

最初に結論

参照設定に System.IO.Compression と System.IO.Compression.FileSystem の2つのアセンブリを追加し、さらに using (VB.NET ではImports) ステートメントで System.IO.Compression 名前空間を参照させましょう。

経緯

.NET Framework 4.5 以降で ZIP ファイルの作成、更新、解凍を行う機能が搭載されました。
ネット上には有志の方が、サンプルコードなどの情報を提供してくださっています。

任意のひとつのファイルをもとにZIPファイルを作成しようとして、ネット上の情報をもとに次のような CreateEntryFromFile を使用したコードを作成しました。
プロジェクトは今回「コンソールアプリケーション」テンプレートから作成し、参照設定に System.IO.Compression と System.IO.Compression.FileSystem の2つのアセンブリを追加してあります。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TESTAPP
{
    class Program
    {
        static void Main(string[] args)
        {
            var targetFilePath = "SAMPLE.TXT";
            var zipFilePath = "SAMPLE.ZIP";
            if (System.IO.File.Exists(zipFilePath))
                System.IO.File.Delete(zipFilePath);
            using (var arc = System.IO.Compression.ZipFile.Open(zipFilePath, System.IO.Compression.ZipArchiveMode.Create))
            {
                arc.CreateEntryFromFile(targetFilePath, System.IO.Path.GetFileName(targetFilePath));
            }
        }
    }
}

しかし

エラー 1 'System.IO.Compression.ZipArchive' に 'CreateEntryFromFile' の定義が含まれておらず、型 'System.IO.Compression.ZipArchive' の最初の引数を受け付ける拡張メソッドが見つかりませんでした。using ディレクティブまたはアセンブリ参照が不足しています。

とのエラーで、ビルドに失敗しました(もっとも、インテリセンスに "CreateEntryFromFile" が出てきません)

MSDN の情報では ZipArchiveZipArchiveExtensions の2つのクラスのメンバーとして登録されています。で、よく見ると前者には「拡張メソッド」と書かれており、後者のシグネイチャは第一引数が "this ZipArchive destination," となっていることに気づきました。
このメソッドは、System.IO.Compression.ZipArchiveExtensions クラスが提供する、System.IO.Compression.ZipArchive クラスへの拡張メソッドだったのです。

コードの先頭あたりに

using System.IO.Compression;

を追加して、万事うまくいきました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0