当前位置: 首页 > article >正文

C# 获取硬件信息工具类

写在前面

通过性能计数器类 PerformanceCounter 传入计数器名称,获取对应的系统指标数据,以便进行分析和参考。
通过System.Management类库中的ManagementObjectSearcher类实现对管理信息的查询,比如:主板信息、内存信息、硬盘信息、显卡信息、声卡信息、网卡信息、生产商和生产日期等。

需引入一下命名空间:

using System.Diagnostics;
using System.Management;
using System.Net.NetworkInformation;
using System.Text.Json;

代码实现

    public class DeviceInfoHelper
    {
        /// <summary>
        /// 获取CPU利用率
        /// </summary>
        public static float GetCpuStatus()
        {
            // 创建对 CPU 占用百分比的性能计数器。
            var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            if (cpuCounter != null)
            {
                return cpuCounter.NextValue();
            }
            return 0;
        }

        /// <summary>
        /// 获取剩余内存
        /// </summary>
        public static float GetAvailableMemory()
        {
            // 创建内存占用字节数的性能计数器
            var ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            if (ramCounter != null)
            {
                return ramCounter.NextValue();
            }
            return 0;
        }

        /// <summary>
        /// 获取当前进程CPU和内存使用情况
        /// </summary>
        public static Tuple<float, float> GetCurrentProcessorUsage()
        {
            var processName = Process.GetCurrentProcess().ProcessName;
            var theCPUCounter = new PerformanceCounter("Process", "% Processor Time", processName);
            var theMemCounter = new PerformanceCounter("Process", "Working Set", processName);
            return new Tuple<float, float>(theCPUCounter.NextValue(), theMemCounter.NextValue());
        }

        /// <summary>
        /// 获取硬件信息摘要
        /// </summary>
        public static string GetHardwareSummary()
        {
            var hdInfo = new HardwardSummary
            {
                MainboardName = "未知",
                MemorySize = "未知",
                HarddiskSize = "未知",
                VideocardName = "未知",
                SoundcardName = "未知",
                NetworkcardName = "未知",
                ManufacturerName = "未知",
                ManufactureDate = "未知"
            };

            #region 主板信息

            try
            {
                ManagementObjectSearcher myMainboard = new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");
                foreach (ManagementObject board in myMainboard.Get())
                {
                    hdInfo.MainboardName = board["Product"].ToString();
                }
            }
            catch (Exception ex)
            {
                hdInfo.MainboardName = "未知";
            }

            #endregion

            #region 内存信息

            try
            {
                ManagementObjectSearcher myMemory = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMemory");
                //定义内存总大小变量
                double MemorySize = 0;
                foreach (ManagementObject obj in myMemory.Get())
                {
                    //将内存大小换算成G单位
                    MemorySize += Convert.ToDouble(obj["Capacity"]) / 1024 / 1024 / 1024;
                }
                hdInfo.MemorySize = MemorySize.ToString() + "G";
            }
            catch (ManagementException e)
            {
                hdInfo.MemorySize = "未知";
            }

            #endregion

            #region 硬盘信息

            try
            {
                //获取本机所有硬盘信息  
                ManagementObjectSearcher myHarddisk = new ManagementObjectSearcher("select * from Win32_DiskDrive");
                foreach (ManagementObject drive in myHarddisk.Get())
                {
                    //获取硬盘容量
                    var capacity = (Convert.ToDouble(drive["Size"]) / 1024 / 1024 / 1024).ToString("0.00") + "G";
                    //获取硬盘类型
                    var mediaType = drive["MediaType"];
                    hdInfo.HarddiskSize = capacity.ToString() + "|" + mediaType.ToString();
                }
            }
            catch (Exception ex)
            {
                hdInfo.HarddiskSize = "未知";
            }

            #endregion

            #region 显卡信息

            try
            {
                ManagementObjectSearcher myVideoObject = new ManagementObjectSearcher("select * from Win32_VideoController");
                foreach (ManagementObject obj in myVideoObject.Get())
                {
                    hdInfo.VideocardName = obj["Name"].ToString();
                }
            }
            catch (ManagementException ex)
            {
                hdInfo.VideocardName = "未知";
            }

            #endregion

            #region 声卡信息

            try
            {
                // 创建WMI搜索对象
                ManagementObjectSearcher mySoundcard = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SoundDevice");
                // 遍历搜索结果
                foreach (ManagementObject mo in mySoundcard.Get())
                {
                    // 获取声卡名称
                    hdInfo.SoundcardName = mo.GetPropertyValue("Name").ToString();
                }
            }
            catch (ManagementException ex)
            {
                hdInfo.SoundcardName = "未知";
            }

            #endregion

            #region 网卡信息

            try
            {
                // 获取本地网络接口信息 
                NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in nics)
                {
                    // 如果是RJ45网卡 
                    if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                    {
                        string S1 = (string)adapter.Description;
                        if (S1.Contains("PCI"))
                        {
                            hdInfo.NetworkcardName = S1;
                        }
                    }
                }
            }
            catch (ManagementException ex)
            {
                hdInfo.NetworkcardName = "未知";
            }

            #endregion

            #region 生产商和生产日期

            try
            {
                //获取生产商
                ManagementObjectSearcher ManufacturerInfo = new ManagementObjectSearcher("select * from Win32_ComputerSystem");
                foreach (ManagementObject obj in ManufacturerInfo.Get())
                {
                    hdInfo.ManufacturerName = obj["Manufacturer"].ToString();
                }
                //获取生产日期
                ConnectionOptions options = new ConnectionOptions();
                ManagementScope scope = new ManagementScope("\\\\.\\root\\cimv2", options);
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_BIOS");
                ManagementObjectSearcher BoisInfo = new ManagementObjectSearcher(scope, query);
                foreach (ManagementObject mo in BoisInfo.Get())
                {
                    string StrManufactureDate = mo["ReleaseDate"].ToString().Substring(0, 8);
                    DateTime DT = DateTime.ParseExact(StrManufactureDate, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                    hdInfo.ManufactureDate = String.Format("{0:d}", DT);
                }
            }
            catch (Exception ex)
            {
                hdInfo.ManufacturerName = "未知";
                hdInfo.ManufactureDate = "未知";
            }

            #endregion

            return JsonSerializer.Serialize(hdInfo);
        }
    }

    public class HardwardSummary
    {
        public string MainboardName { get; set; }
        public string MemorySize { get; set; }
        public string HarddiskSize { get; set; }
        public string VideocardName { get; set; }
        public string SoundcardName { get; set; }
        public string NetworkcardName { get; set; }
        public string ManufacturerName { get; set; }
        public string ManufactureDate { get; set; }
    }


http://www.kler.cn/a/148976.html

相关文章:

  • Java结合ElasticSearch根据查询关键字,高亮显示全文数据。
  • Ruby编程语言全景解析:从基础到进阶
  • 基于微信小程序的乡村研学游平台设计与实现,LW+源码+讲解
  • 基于Java Web的传智播客crm企业管理系统的设计与实现
  • 06.VSCODE:备战大项目,CMake专项配置
  • TortoiseSVN提示服务器凭证检核错误:站点名称不符
  • 鸿蒙应用开发-初见:入门知识、应用模型
  • MySQL数据库编程进阶
  • 【NGINX--8】HTTP/2
  • Jmeter和Testlink自动化测试框架研究与实施
  • 每日一练:简易计算器
  • PHP众筹系统源码+支持报名众筹+商品众筹+无偿众筹+市面上所有的众筹模式 附带完整的搭建教程
  • 不小心删除了短信,如何在 Android 上恢复已删除的短信
  • 【brpc学习实践八】bvar及其应用
  • Deep Image Prior
  • 配置服务器免密登录
  • 【VRTK】【VR开发】【Unity】9-瞬移
  • Flink流批一体计算(21):Flink SQL之Flink DDL
  • OpenCV快速入门【完结】:总目录——初窥计算机视觉
  • 统计元音字母c语言
  • 手把手教你如何实现List——ArrayList
  • 鸿蒙(HarmonyOS)应用开发——应用程序入口UIAbility(题目答案)
  • C#,数值计算——插值和外推,径向基函数插值(RBF_inversemultiquadric)的计算方法与源程序
  • 基于binlog实现一些业务(Binlog4j)
  • 哈希表——闭散列表
  • 分析:为什么有些pdf打开之后无法编辑?