CR的代码文本

all for learning about the world
  订阅 订阅  :: 管理

C# 获取当前操作系统是32位还是64位

Posted on 2014-03-10 14:14  mumuliang  阅读(2480)  评论(2编辑  收藏  举报

注:判断整型的长度的方式,只有在AnyCPU编译模式下才有用。因此更好的办法是获取真的地址总线位宽(使用WMI,windows management instruementation)。

 

.NET 2.0

add reference, System.Management

using System.Management;
...

        public static int GetOSBit()
        {
            try
            {
                string addressWidth = String.Empty;
                ConnectionOptions mConnOption = new ConnectionOptions();
                ManagementScope mMs = new ManagementScope(@"\\localhost", mConnOption);
                ObjectQuery mQuery = new ObjectQuery("select AddressWidth from Win32_Processor");
                ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mMs, mQuery);
                ManagementObjectCollection mObjectCollection = mSearcher.Get();
                foreach (ManagementObject mObject in mObjectCollection)
                {
                    addressWidth = mObject["AddressWidth"].ToString();
                }
                return Int32.Parse(addressWidth);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return 32;
            }
        }