zoukankan      html  css  js  c++  java
  • 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;
    }
    }
    }

    以上为两种实现方法。

  • 相关阅读:
    Spring Cloud Eureka的学习
    Maven环境配置
    Maven解决静态资源过滤问题
    Linux Desktop Entry文件配置解析
    iptables规则持久化
    Markdown学习总结
    输vim /etc/rc.d/init.d/mysqld 报错 …..localdomain.pid
    UE4 集成讯飞听写插件
    单机梦幻西游
    使用A*寻路小记
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/4103977.html
Copyright © 2011-2022 走看看