C# 判斷作業系統的位元

來源:互聯網
上載者:User

標籤: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# 判斷作業系統的位元

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.