System.BadImageFormatException (その1 DLLのLoad)

ダイナミック リンク ライブラリ (DLL) または実行可能プログラムのファイル イメージが無効である場合にスローされる例外。
今回は、Windows システム DLLを、.NET Framework アセンブリであるかのように読み込もうとした場合におきる例外を実験。

[実験ソース(C#)]


using System;

using System.Reflection;

using System.IO;



namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string path = Environment.ExpandEnvironmentVariables("%windir%");

            path = Path.Combine(path, @"System32\user32.dll");

            Assembly assem = Assembly.LoadFile(path);

        }

    }

}

[結果]


ハンドルされていない例外: System.BadImageFormatException: モジュールはアセンブリ マニフェストを含んでいなければなりません。 (HRESULT からの例外: 0x80131018)
場所 System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
場所 System.Reflection.Assembly.LoadFile(String path)
場所 ConsoleApplication1.Program.Main(String[] args) 場所 Program.cs:行 13

[対処など]
DllImport を使って、以下のように書き換える。

using System;

using System.Runtime.InteropServices;



namespace ConsoleApplication1

{

    class Program

    {

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]

        public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type);



        static void Main(string[] args)

        {

            MessageBox(IntPtr.Zero, "テスト""タイトル"0);

        }

    }

}