1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

System.Reflection.ReflectionTypeLoadExceptionが出ても中身を見たい場合

Posted at

問題の所在

 不完全なアセンブリをSystem.Reflection.Assembly.LoadFrom()などで読み込むと、System.Reflection.ReflectionTypeLoadExceptionが投げられてしまいます。

using System.Reflection;

static void Main(string[] args)
{
  var asm = Assembly.LoadFrom("incomplete.dll");
  foreach(var type in asm.GetTypes()) /* <- 不完全なアセンブリだとGetTypes()が ReflectionTypeLoadException を送出 */
  {
    Console.WriteLine($"{type.FullName} : {type.BaseType?.FullName}");
  }
}

 もちろん、「メソッドをInvokeしたい」など、実際に動かす必要がある場合は不足しているアセンブリを見つけてきて解決しなければなりません。
一方で、アセンブリのリフレクション情報だけを読み取れればよいというケースも存在します。
そのような場合に活躍するのが Mono.Cecil です。

Mono.Cecil

 Monoプロジェクトで開発されており、Mono DevelopやILSpyなどで採用実績があります[1]。
公式サイトは http://cecil.pe/ です。
Mono.CecilはNuGetで配布されていますので、特別な理由がなければNuGetで取得しましょう。

Mono.Cecilを用いたアセンブリの読み込み

 .NETのものと若干インターフェイスが異なりますが、ほとんど違和感なく使うことができます。

using Mono.Cecil;

static void Main(string[] args)
{
  var asm = AssemblyDefinition.ReadAssembly("incomplete.dll");
  foreach(var type in asm.Types)
  {
    Console.WriteLine($"{type.FullName} : {type.BaseType?.FullName}");
    // メソッドやプロパティの列挙も可能. 
  }
}

脚注

[1] : http://www.mono-project.com/docs/tools+libraries/libraries/Mono.Cecil/

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?