温馨提示×

c#怎么获取硬件信息

c#
小亿
116
2024-08-26 14:30:34
栏目: 编程语言

在C#中,可以使用System.Management命名空间下的ManagementObject类来获取硬件信息。以下是一个示例代码,演示如何获取计算机的一些硬件信息(例如处理器、内存、硬盘):

using System;
using System.Management;

class Program
{
    static void Main()
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
        foreach (ManagementObject obj in searcher.Get())
        {
            Console.WriteLine("Processor: {0}", obj["Name"]);
        }

        searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMemory");
        foreach (ManagementObject obj in searcher.Get())
        {
            Console.WriteLine("Memory: {0} MB", Convert.ToInt64(obj["Capacity"]) / (1024 * 1024));
        }

        searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDisk WHERE DriveType=3");
        foreach (ManagementObject obj in searcher.Get())
        {
            Console.WriteLine("Hard Drive: {0} GB", Convert.ToInt64(obj["Size"]) / (1024 * 1024 * 1024));
        }
    }
}

这段代码将获取计算机的处理器、内存和硬盘信息,并输出到控制台。你也可以根据自己的需求,使用不同的WMI查询语句来获取其他硬件信息。

0