C#如何判断操作系统位数是32位还是64位

发布于 2017-10-27 | 作者: 憨熊之家 | 来源: www.cnblogs.com | 转载于: www.cnblogs.com

方法一:
对于C#来说,调用WMI是一种简单易行的方式。我们可以用Win32_Processor类里面的AddressWidth属性来表示系统的位宽。AddressWidth的值受CPU和操作系统的双重影响。
具体的值如下面的表格所示:

  32bit OS 64bit OS
32bit CPU AddressWidth = 32 N/A
64bit CPU AddressWidth = 32 AddressWidth = 64


可以用下面的C#代码得到AddressWidth的值
(注意需添加引用System.Management)

public static string Detect3264()
{
	ConnectionOptions oConn = new ConnectionOptions();
	System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\localhost", oConn);
	System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select AddressWidth from Win32_Processor");
	ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
	ManagementObjectCollection oReturnCollection = oSearcher.Get();
	string addressWidth = null;
	
	foreach (ManagementObject oReturn in oReturnCollection)
	{
		addressWidth = oReturn["AddressWidth"].ToString();
	}
	
	return addressWidth;
}

方法二:

bool type;
type = Environment.Is64BitOperatingSystem;
Console.WriteLine(type);

如返回值为True则表示是64位,如返回值为False则表示为32位。

方法三:
这个方法也是最直接的方法,但是有条件限制,例用IntPtr结构的size属性来查看系统的位宽
命名空间是System;
前题是程序需要采用any/CPU的方式进行编辑;
正常情况下int的位宽是4位,即是32位操作系统。

if (IntPtr.Size == 8)
{ 
	//64 bit
}
else if (IntPtr.Size == 4)
{ 
	//32 bit
}
else 
{
	//...NotSupport
}

方法四:
64位Wnidows 里面有个叫Wow64 的模拟器技术,可以使32位的程序在64位Windows 上运行。 当你想在程序里面针对32b位/ 64位系统执行不同代码的时候, 需要判断操作系统是32位还是64位。 使用 Windows API函数 GetNativeSystemInfo 可以获得这个信息。

SYSTEM_INFO si; 
GetNativeSystemInfo(&si); 
if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 || si.wProcessorArchitecture != PROCESSOR_ARCHITECTURE_IA64 ) 
{
	//64 位操作系统 
} 
else 
{ 
	// 32 位操作系统 
}

另外,Windows API 还提供了 IsWow64Process 函数判断程序是不是运行在Wow64模拟器之上。

BOOL bIsWow64 = FALSE; 
IsWow64Process(GetCurrentProcess(), &bIsWow64);

需要注意是GetNativeSystemInfo  函数从Windows XP 开始才有, 而 IsWow64Process  函数从 Windows XP with SP2 以及 Windows Server 2003 with SP1 开始才有。 所以使用该函数的时候最好用GetProcAddress。

typedef void (WINAPI *LPFN_PGNSI)(LPSYSTEM_INFO); 

typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);     

LPFN_PGNSI pGNSI = (LPFN_PGNSI ) GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetNativeSystemInfo"); 

LPFN_ISWOW64PROCESS    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")),"IsWow64Process");