工作但崩溃很奇怪,但是硬件状态会打印在控制台窗口中,但是当我运行它时我的应用程序崩溃了。我在表格的负载上有它。 错误说:对象引用未设置为对象的实例
以下是代码:
//硬件检查
ManagementObjectSearcher deviceList =
new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity");
// Any results? There should be!
if (deviceList != null)
// Enumerate the devices
foreach (ManagementObject device in deviceList.Get())
{
// To make the example more simple,
string name = device.GetPropertyValue("Name").ToString();
string status = device.GetPropertyValue("Status").ToString();
// Uncomment these lines and use the "select * query" if you
// want a VERY verbose list
// foreach (PropertyData prop in device.Properties)
// Console.WriteLine( "\t" + prop.Name + ": " + prop.Value);
// More details on the valid properties:
//
Console.WriteLine("Device name: {0}", name);
Console.WriteLine("\tStatus: {0}", status);
// Part II, Evaluate the device status.
bool working = ((status == "OK") || (status == "Degraded")
|| (status == "Pred Fail"));
Console.WriteLine("\tWorking?: {0}", working);
}
答案 0 :(得分:0)
因此,在处理管理对象时,您的问题是所有属性都可以返回null
,您需要始终考虑到此问题以及其他一些问题:
由于Name
和Status
属性都是字符串,因此您可以在不调用.ToString()
的情况下强制转换它们,并使用?? string.Empty
替换null
个值一个空字符串。
// Hardware check
using (ManagementObjectSearcher deviceSearcher = new ManagementObjectSearcher("Select Name, Status from Win32_PnPEntity"))
using (ManagementObjectCollection devices = deviceSearcher.Get())
{
// Enumerate the devices
foreach (ManagementObject device in devices)
{
// To make the example more simple,
string name = (string)device.GetPropertyValue("Name") ?? string.Empty;
string status = (string)device.GetPropertyValue("Status") ?? string.Empty;
// Uncomment these lines and use the "select * query" if you
// want a VERY verbose list
// foreach (PropertyData prop in device.Properties)
// Console.WriteLine("\t{0}: {1}", prop.Name, prop.Value);
// More details on the valid properties:
//
Console.WriteLine("Device name: {0}", name);
Console.WriteLine("\tStatus: {0}", status);
// Part II, Evaluate the device status.
bool working = status == "OK" || status == "Degraded" || status == "Pred Fail";
Console.WriteLine("\tWorking?: {0}", working);
}
}