.Net Framework 4.0 - MethodAccessException was unhandled by user code


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/

VB.Net

<system.security.securitysafecritical()>

C#

[SecuritySafeCritical]

Config XML

<configuration>
        <runtime>
        <netfx40_legacysecuritypolicy enabled="true" />
        </runtime>
</configuration>

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.