WPF 获取电脑硬件信息并生成 JSON 文件(含 MAC 地址)
要在 WPF 中生成电脑硬件信息的 JSON 文件,可以使用 System.Management 命名空间中的 ManagementObject 类来获取硬件信息,以及 Newtonsoft.Json 库来生成 JSON 文件。
首先,需要在项目中添加对 System.Management 和 Newtonsoft.Json 的引用。
然后,可以创建一个名为 HardwareInfo 的类,用于存储硬件信息。在该类中,可以定义需要的硬件信息属性,例如 MAC 地址:
public class HardwareInfo
{
public string MacAddress { get; set; }
// 添加其他硬件信息属性
}
接下来,在程序运行时,可以使用 ManagementObject 类来获取硬件信息。可以编写一个名为 GetMacAddress 的方法来获取 MAC 地址:
private static string GetMacAddress()
{
ManagementClass mc = new ManagementClass('Win32_NetworkAdapterConfiguration');
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo['IPEnabled'])
{
return mo['MacAddress'].ToString();
}
}
return string.Empty;
}
然后,在主窗口的 Loaded 事件中调用 GetMacAddress 方法,并生成 JSON 文件:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// 创建 HardwareInfo 对象并设置属性值
HardwareInfo hardwareInfo = new HardwareInfo();
hardwareInfo.MacAddress = GetMacAddress();
// 设置其他硬件信息属性
// 将 HardwareInfo 对象转换为 JSON 字符串
string json = JsonConvert.SerializeObject(hardwareInfo, Formatting.Indented);
// 保存 JSON 字符串到文件
File.WriteAllText('pc.info', json);
}
这样,在程序运行时,将在程序所在目录下生成一个名为 pc.info 的 JSON 文件,其中包含了硬件信息,包括 MAC 地址。
注意:获取硬件信息需要管理员权限,因此需要以管理员身份运行程序。
原文地址: http://www.cveoy.top/t/topic/qFLU 著作权归作者所有。请勿转载和采集!