日期:2014-05-17 浏览次数:21082 次
//获取硬盘的物理id号 public static string getDiskMac() { try { string HDid = null; ManagementClass cimobject = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = cimobject.GetInstances(); foreach(ManagementObject mo in moc) { HDid = (string)mo.Properties["PNPDeviceID"].Value; break; } return HDid; } catch { return ""; } }
------解决方案--------------------
对于一些比如光驱之类的介质,当还没有被加载时,GetPropertyValue("VolumeSerialNumber")会返回null,直接ToString()自然会报错。
object o = id.GetPropertyValue("VolumeSerialNumber");
if(o != null)
{
hardDiskID = o.ToString().Trim();
this.label1.Text += string.Format("磁盘序列号为{0} \t\n", hardDiskID);
}
------解决方案--------------------
private List<string> GetMoc() { List<string> str_list = new List<string>(); ManagementClass mcCpu = new ManagementClass("win32_Processor"); //ManagementObjectCollection mocCpu = mcCpu.GetInstances(); //foreach (ManagementObject m in mocCpu) //{ // str[0] = m["ProcessorId"].ToString(); //} ManagementClass mcHD = new ManagementClass("win32_logicaldisk"); ManagementObjectCollection mocHD = mcHD.GetInstances(); foreach (ManagementObject m in mocHD) { str_list.Add(m["DeviceID"].ToString() + ":" + m["VolumeSerialNumber"].ToString()); } return str_list; }