C# - Hardware status check, working but crashing -
working crashing weird say, hardware status gets printed in console window application crash when run this. have on load of form. error says: object reference not set instance of object
and here code:
// hardware check
managementobjectsearcher devicelist = new managementobjectsearcher("select name, status win32_pnpentity"); // results? there should be! if (devicelist != null) // enumerate devices foreach (managementobject device in devicelist.get()) { // create illustration more simple, string name = device.getpropertyvalue("name").tostring(); string status = device.getpropertyvalue("status").tostring(); // uncomment these lines , utilize "select * query" if // want verbose list // foreach (propertydata prop in device.properties) // console.writeline( "\t" + prop.name + ": " + prop.value); // more details on valid properties: // console.writeline("device name: {0}", name); console.writeline("\tstatus: {0}", status); // part ii, evaluate device status. bool working = ((status == "ok") || (status == "degraded") || (status == "pred fail")); console.writeline("\tworking?: {0}", working); }
so problem when working management objects properties can homecoming null , need business relationship @ times other issues:
since both name , status properties strings anyway, can cast them such without calling .tostring() , utilize ?? string.empty replace null values empty string.
// hardware check using (managementobjectsearcher devicesearcher = new managementobjectsearcher("select name, status win32_pnpentity")) using (managementobjectcollection devices = devicesearcher.get()) { // enumerate devices foreach (managementobject device in devices) { // create illustration more simple, string name = (string)device.getpropertyvalue("name") ?? string.empty; string status = (string)device.getpropertyvalue("status") ?? string.empty; // uncomment these lines , utilize "select * query" if // want verbose list // foreach (propertydata prop in device.properties) // console.writeline("\t{0}: {1}", prop.name, prop.value); // more details on valid properties: // console.writeline("device name: {0}", name); console.writeline("\tstatus: {0}", status); // part ii, evaluate device status. bool working = status == "ok" || status == "degraded" || status == "pred fail"; console.writeline("\tworking?: {0}", working); } } c#
No comments:
Post a Comment