.Net Framework 4.0 - MethodAccessException was unhandled by user code

Posted: 12/16/2010

In the .Net Framework 4.0 some security changes have been made which will cause issues with legacy PInvoke's to the Windows API's in library files. I'm going to link to some blog posts of others that go into this in more detail but I'm going to share the fix that they provided. There are two options. The first is to set a flag that tells the assembly to run in legacy mode. The second (the one I choose) is to mark the methods with the [SecuritySafeCritial] flag.

  1. http://msdn.microsoft.com/en-us/library/dd409253.aspx
  2. http://msdn.microsoft.com/en-us/library/bb397858.aspx
  3. http://www.comanswer.com/question/net-4-method-security-exception-when-pinvoking
  4. http://blogs.rev-net.com/ddewinter/2009/05/20/opting-out-of-security-changes-in-net-4/





Config XML

           <netfx40_legacysecuritypolicy enabled="true" />