title: How to catch LoadLibrary exception of "Bad Image"
body: <p>When I am trying to load a binary file with a magic start of &quot;DCS&quot; instead of the common &quot;MZ&quot;, it fails with an error:</p>
  <blockquote>
  <p>C:\Windows\winsxs\x86_wcf-system.identitymodel_b03f5f7f11d50a3a_10.0.19041.1_none_e690fdc7d17e3f70\System.IdentityModel.dll is either not designed to run on Windows or it contains an error. Try installing the program again using the original installation media or contact your system administator or the software vendor for support. Error status: 0xc000012f.</p>
  </blockquote>
  <p>Even when I added <code>try...catch</code>:</p>
  <pre class="lang-cs prettyprint-override"><code>[DllImport(&quot;kernel32.dll&quot;, CharSet = CharSet.Unicode, SetLastError = true)]
  internal static extern SafeLoadLibraryHandle LoadLibraryEx(string name, IntPtr reserved, LoadLibraryFlags flags);
  
  public enum LoadLibraryFlags
  {
      DontResolveDllReferences = 0x00000001,
  }
  
  ...
  
  string name = @&quot;C:\Windows\winsxs\x86_wcf-system.identitymodel_b03f5f7f11d50a3a_10.0.19041.1_none_e690fdc7d17e3f70\System.IdentityModel.dll&quot;;  
  
  SafeLoadLibraryHandle ret = null;
  try
  {
     ret = Win32NativeMethods.LoadLibraryEx(name, IntPtr.Zero, flags);
  }
  catch (Exception)
  {
  
      //throw;
  }
  
  </code></pre>
  <p>My current workaround is to check if the image starts with &quot;MZ&quot;, if not, ignore it.<br />
  But I thought to check if someone knows a better way to handle it.</p>