How to detect Windows 64-bit platform with .NET?

前端 未结 29 2742
野性不改
野性不改 2020-11-22 04:53

In a .NET 2.0 C# application I use the following code to detect the operating system platform:

string os_platform = System.Environment.OSVersion.Platform.ToS         


        
29条回答
  •  臣服心动
    2020-11-22 05:11

    This is just an implementation of what's suggested above by Bruno Lopez, but works on Win2k + all WinXP service packs. Just figured I'd post it so other people didn't have roll it by hand. (would have posted as a comment, but I'm a new user!)

    [DllImport("kernel32", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
    public extern static IntPtr LoadLibrary(string libraryName);
    
    [DllImport("kernel32", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
    public extern static IntPtr GetProcAddress(IntPtr hwnd, string procedureName);
    
    private delegate bool IsWow64ProcessDelegate([In] IntPtr handle, [Out] out bool isWow64Process);
    
    public static bool IsOS64Bit()
    {
        if (IntPtr.Size == 8 || (IntPtr.Size == 4 && Is32BitProcessOn64BitProcessor()))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    private static IsWow64ProcessDelegate GetIsWow64ProcessDelegate()
    {
      IntPtr handle = LoadLibrary("kernel32");
    
      if ( handle != IntPtr.Zero)
      {
        IntPtr fnPtr = GetProcAddress(handle, "IsWow64Process");
    
        if (fnPtr != IntPtr.Zero)
        {
          return (IsWow64ProcessDelegate)Marshal.GetDelegateForFunctionPointer((IntPtr)fnPtr, typeof(IsWow64ProcessDelegate));
        }
      }
    
      return null;
    }
    
    private static bool Is32BitProcessOn64BitProcessor()
    {
      IsWow64ProcessDelegate fnDelegate = GetIsWow64ProcessDelegate();
    
      if (fnDelegate == null)
      {
        return false;
      }
    
      bool isWow64;
      bool retVal = fnDelegate.Invoke(Process.GetCurrentProcess().Handle, out isWow64);
    
      if (retVal == false)
      {
        return false;
      }
    
      return isWow64;
    }
    

提交回复
热议问题