標籤:io ar os sp for on 問題 cti 代碼
判斷作業系統的位元有一下幾種方法:
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# 判斷作業系統的位元