I have the below code which goes through and returns disk information. When running I notice that some WMI properties are not available on my computer (ie FirmwareRevision).
So, when I run the code VS is crashing out stating “not found”. any idea how I put an exception catch in to state on the output of the object not found to state “Not Available”.
I have been reading on exception catch but my amateurish way thus far is to explicitly define the exception I want to use…this program intends to run on loads of different servers so hoping it can intelligently figure out the WMI objects that any one server may not have.
The code is the below and currently it fails on (the last line):
“lblFirmware.Text = “Firmware: ”
+moDisk[“FirmwareRevision”].ToString();”
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using Microsoft.Win32;
namespace diskdrive_info
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Get all the disk drives
ManagementObjectSearcher mosDisk = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
// Loop through each object (disk) retrieved by WMI
foreach (ManagementObject moDisk in mosDisk.Get())
{
cmbHdd.Items.Add(moDisk["Model"].ToString());
}
}
private void cmbHdd_SelectedIndexChanged(object sender,EventArgs e)
{
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
foreach (ManagementObject moDisk in mosDisks.Get())
{
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
lblModel.Text = "Model: " + moDisk["Model"].ToString();
lblCapacity.Text = "Capacity: " + moDisk["Size"].ToString();
lblPartitions.Text = "Partitions: " + moDisk["Partitions"].ToString();
lblSectors.Text = "Sectors: " + moDisk["SectorsPerTrack"].ToString();
lblSignature.Text = "Signatures: " +moDisk["Signature"].ToString();
lblFirmware.Text = "Firmware: " +moDisk["FirmwareRevision"].ToString();
}
}
}
}
Try this