1

I have the below code which is throwing a BadImageFormatException. The DLL it's loading is 32bit. The web server is running Windows 64bit but the application pool is set to Enable 32 bit. Is there any way I can get this to work?

public class HomeController : Controller
{
    [DllImport("CDCrypt.dll")]
    [return: MarshalAs(UnmanagedType.LPStr)]
    public static extern String Encrypt 
        ([MarshalAs(UnmanagedType.LPStr)] String aName);

    [DllImport("CDCrypt.dll")]
    [return: MarshalAs(UnmanagedType.LPStr)]
    public static extern String Decrypt
        ([MarshalAs(UnmanagedType.LPStr)] String aName);

    public ActionResult Index()
    {
        try
        {
            ViewBag.EncryptString = Encrypt("test");
        }
        catch (Exception e)
        {
            ViewBag.EncryptString =
                "Stack Trace\r\n:" + "\r\nException: " + e.Message;
            return new HttpStatusCodeResult(500);
        }
        return View();
    }

    public ActionResult Up()
    {
        ViewBag.Up = "You can see me";
        return View();
    }
}
SteveC
  • 15,808
  • 23
  • 102
  • 173
Jon
  • 38,814
  • 81
  • 233
  • 382

1 Answers1

1

Both the library and the consumer have to be the same. So determine what your lib you are calling is and ensure you are compiling for that type. Now - IIS itself (at least v 6) can only run one mode OR the other for everything so it either needs to be set for 64 or 32 bit across the board . See this http://support.microsoft.com/kb/894435

in conjunction with:

http://social.msdn.microsoft.com/Forums/en-US/netfx64bit/thread/35b09f74-1d8e-4676-90e3-c73a439bf632/

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Its using iis 7 and i tried compiling the site against x86 but no luck – Jon Jun 06 '11 at 17:05
  • hmm.. iis 7 then I think only requires the worker process to be 32 bit - put some code in to ensure you are 32 bit as a double check - http://stackoverflow.com/questions/1953377/how-to-know-a-process-is-32-bit-or-64-bit-programmatically – Adam Tuliper Jun 06 '11 at 17:10
  • I added the code in that link, compiled against x86 ran the web page and it says its 32bit which would indicate all is ok so why the exception http://encrypt.tbmaster.co.uk/home/up shows the output. http://encrypt.tbmaster.co.uk/home/index is the problem – Jon Jun 06 '11 at 17:23
  • I recompiled against x64 and now get a YSOD saying it cant find the main web app dll which would indicate it is running in 32bit maybe – Jon Jun 06 '11 at 17:29
  • Ive installed Windows 2008 and can replicate the problem and can see by turning Enable32bit mode on and off that its working. I just dont know how to fix this issue – Jon Jun 12 '11 at 08:11