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

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

    Include the following code into a class in your project:

        [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool wow64Process);
    
        public static int GetBit()
        {
            int MethodResult = "";
            try
            {
                int Architecture = 32;
    
                if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) || Environment.OSVersion.Version.Major >= 6)
                {
                    using (Process p = Process.GetCurrentProcess())
                    {
                        bool Is64Bit;
    
                        if (IsWow64Process(p.Handle, out Is64Bit))
                        {
                            if (Is64Bit)
                            {
                                Architecture = 64;
    
                            }
    
                        }
    
                    }
    
                }
    
                MethodResult = Architecture;
    
            }
            catch //(Exception ex)
            {
                //ex.HandleException();
            }
            return MethodResult;
        }
    

    Use it like so:

    string Architecture = "This is a " + GetBit() + "bit machine";
    

提交回复
热议问题