写一段采集计算机硬件信息的C#代码
时间: 2024-03-12 11:43:05 浏览: 96
以下是一个简单的采集计算机硬件信息的 C# 代码示例:
```csharp
using System;
using System.Management;
namespace HardwareInfoCollector
{
class Program
{
static void Main(string[] args)
{
// 获取计算机系统信息
ManagementObjectSearcher computerSystemSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
foreach (ManagementObject obj in computerSystemSearcher.Get())
{
Console.WriteLine("Manufacturer: " + obj["Manufacturer"].ToString());
Console.WriteLine("Model: " + obj["Model"].ToString());
Console.WriteLine("Total Physical Memory: " + (Convert.ToDouble(obj["TotalPhysicalMemory"]) / (1024 * 1024 * 1024)).ToString("0.00") + " GB");
}
// 获取 CPU 信息
ManagementObjectSearcher cpuSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
foreach (ManagementObject obj in cpuSearcher.Get())
{
Console.WriteLine("Processor Name: " + obj["Name"].ToString());
Console.WriteLine("Number of Cores: " + obj["NumberOfCores"].ToString());
Console.WriteLine("Max Clock Speed: " + (Convert.ToDouble(obj["MaxClockSpeed"]) / 1000).ToString("0.00") + " GHz");
}
// 获取硬盘信息
ManagementObjectSearcher diskDriveSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject obj in diskDriveSearcher.Get())
{
Console.WriteLine("Model: " + obj["Model"].ToString());
Console.WriteLine("Size: " + (Convert.ToDouble(obj["Size"]) / (1024 * 1024 * 1024)).ToString("0.00") + " GB");
}
// 获取操作系统信息
ManagementObjectSearcher operatingSystemSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
foreach (ManagementObject obj in operatingSystemSearcher.Get())
{
Console.WriteLine("Operating System Name: " + obj["Caption"].ToString());
Console.WriteLine("Version: " + obj["Version"].ToString());
}
Console.ReadKey();
}
}
}
```
这段代码使用了 System.Management 命名空间中的 ManagementObjectSearcher 类来查询计算机硬件信息。你可以根据自己的需求修改代码,获取特定的硬件信息。
阅读全文