日期:2014-05-17  浏览次数:21082 次

获取磁盘序列号,出现未将对象引用到设置的实例的问题?
代码如下:
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;

namespace Ex189_读取磁盘序列号
{
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
  try
  {
  string hardDiskID = null;
  ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_logicaldisk");
  foreach (ManagementObject id in searcher.Get())
  {
  hardDiskID = id.GetPropertyValue("VolumeSerialNumber").ToString().Trim();
  this.label1.Text += string.Format("磁盘序列号为{0} \t\n", hardDiskID);
  }
  }
  catch (Exception ex)
  {
  MessageBox.Show(ex.Message);
  }
  }  
  }
}

------解决方案--------------------
C# code

        //获取硬盘的物理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);
}
------解决方案--------------------
C# code
  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;
            }