当前位置:首页 > C#教程 > 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;
}
}
}

以上为两种实现方法。


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐