title: DllImport - An attempt was made to load a program with an incorrect format
body: <p>I want my C# application to conditionally run a native method. Deciding at run time whether to run either the x86 or the x64 version of the dll.</p>
  
  <p><a href="https://stackoverflow.com/questions/1313402/preprocessor-directive-in-c-sharp-for-importing-based-on-platform">This question</a> explains how to choose 32 bit or 64 bit at compile time, but that does not help. I want to make the decision at runtime.</p>
  
  <p>I'm currently doing the following:</p>
  
  <pre><code>[SuppressUnmanagedCodeSecurity]
  internal static class MiniDumpMethods
  {
      [DllImport("dbghelp.dll",
          EntryPoint = "MiniDumpWriteDump",
          CallingConvention = CallingConvention.StdCall,
          CharSet = CharSet.Unicode,
          ExactSpelling = true,
          SetLastError = true)]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool MiniDumpWriteDump(
          IntPtr hProcess,
          uint processId,
          SafeHandle hFile,
          MINIDUMP_TYPE dumpType,
          IntPtr expParam,
          IntPtr userStreamParam,
          IntPtr callbackParam);
  
  [DllImport("dbghelpx86.dll",
  EntryPoint = "MiniDumpWriteDump",
  CallingConvention = CallingConvention.StdCall,
  CharSet = CharSet.Unicode,
  ExactSpelling = true,
  SetLastError = true)]
      [return: MarshalAs(UnmanagedType.Bool)]
      public static extern bool MiniDumpWriteDumpX86(
          IntPtr hProcess,
          uint processId,
          SafeHandle hFile,
          MINIDUMP_TYPE dumpType,
          IntPtr expParam,
          IntPtr userStreamParam,
          IntPtr callbackParam);
  }
  </code></pre>
  
  <p>But when I try to call the x86 method I get the error:</p>
  
  <pre><code>Unhandled Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
     at &lt;exeName&gt;.MiniDumpMethods.MiniDumpWriteDumpX86(IntPtr hProcess, UInt32 processId, SafeHandle hFile, MINIDUMP_TYPE dumpType, IntPtr expParam, IntPtr userStreamParam, IntPtr callbackParam)
  </code></pre>
  
  <p>Any idea how I can conditionally load either the x86 or the x64 version of the dll?</p>
  
  <p>(Note: dbghelpx86.dll is the x86 version of dbghelp.dll that I renamed)</p>
  
  <p>Thanks</p>