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

前端 未结 29 3219
野性不改
野性不改 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:24

    Using dotPeek helps to see how the framework actually does it. With that in mind, here's what I've come up with:

    public static class EnvironmentHelper
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr GetCurrentProcess();
    
        [DllImport("kernel32.dll")]
        static extern IntPtr GetModuleHandle(string moduleName);
    
        [DllImport("kernel32")]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    
        [DllImport("kernel32.dll")]
        static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
    
        public static bool Is64BitOperatingSystem()
        {
            // Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.
            if (IntPtr.Size == 8)
                return true;
            // Check if this process is an x86 process running on an x64 environment.
            IntPtr moduleHandle = GetModuleHandle("kernel32");
            if (moduleHandle != IntPtr.Zero)
            {
                IntPtr processAddress = GetProcAddress(moduleHandle, "IsWow64Process");
                if (processAddress != IntPtr.Zero)
                {
                    bool result;
                    if (IsWow64Process(GetCurrentProcess(), out result) && result)
                        return true;
                }
            }
            // The environment must be an x86 environment.
            return false;
        }
    }
    

    Example usage:

    EnvironmentHelper.Is64BitOperatingSystem();
    

提交回复
热议问题