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;
}
}
}

以上为两种实现方法。

 

posted on   荣锋亮  阅读(1143)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示