首页 > 代码库 > C# 判断操作系统的位数
C# 判断操作系统的位数
判断操作系统的位数有一下几种方法:
1. 特征值IntPtr
2. WMI
1的实现如下:
public static int GetOSInfo()
{
if (IntPtr.Size == 8)
{
return 64;
}
else
{
return 32;
}
}
但是有问题,如果应用运行的是x86 的模式,判断就会有误,如何解决?
添加一下代码:
public static bool Is64BitWindows {
get {
// this is a 64-bit process -> Windows is 64-bit
if (IntPtr.Size == 8)
return true;
// this is a 32-bit process -> we need to check whether we run in Wow64 emulation
bool is64Bit;
if (IsWow64Process(GetCurrentProcess(), out is64Bit)) {
return is64Bit;
} else {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
[DllImport("kernel32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
[DllImport("kernel32")]
public static extern IntPtr GetCurrentProcess();
即可,这样做可以保证是正确的。
2的实现方法如下:
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;
}
}
}
以上为两种实现方法。
C# 判断操作系统的位数