title: AccessViolationException while reading file header when project not marked as 'Prefer 32 bit'
body: <p>The following code is used to read the first byte from a file header.</p>
  
  <p>Running on Windows 8 64bit, this code works when running it under a project which marked as 'AnyCPU - Prefer 32 bit'. (.NET 4.5.1)</p>
  
  <p>If its running under 'AnyCPU' (with 'Prefer 32 bit' unchecked) - it throws </p>
  
  <blockquote>
    <p>"AccessViolationException: Additional information: Attempted to read
    or write protected memory. This is often an indication that other
    memory is corrupt."</p>
  </blockquote>
  
  <p>In previous versions of .NET it worked as 'AnyCPU'.</p>
  
  <p>Why does it behave differently between 'Prefer 32 bit' checked or not?</p>
  
  <p>Why does it behave differently between .net versions?</p>
  
  <pre><code>public class FileParser
  {
      private static uint _hLib;
  
      public static void Parse(string fileName)
      {
          _hLib = LoadLibraryEx(fileName, 0, DONT_RESOLVE_DLL_REFERENCES | LOAD_IGNORE_CODE_AUTHZ_LEVEL);
  
          if (_hLib == 0)
          {
              Console.WriteLine("********* Failed to load {0}.\r\nSpecified file was either not found, or is not a valid PE file.********", fileName);
              return;
          }
  
          ScanHeaders();
      }
  
      private static unsafe void ScanHeaders()
      {
          byte* pDosHeader = (byte*) _hLib;
          Console.WriteLine("pDosHeader[0] = {0}", pDosHeader[0]); // &lt;&lt;---- this is where it throws 'AccessViolationException' 
      }
  
      // From winbase.h in the Win32 platform SDK.
      //
      const uint DONT_RESOLVE_DLL_REFERENCES = 0x00000001;
      const uint LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010;
  
      [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
      static extern uint LoadLibraryEx(string fileName, uint notUsedMustBeZero, uint flags);
  }
  </code></pre>