公司项目要在一个平板上面运行一个软件,然后根据平板的硬盘生成一个唯一ID。因为平板就一个C盘,有的时候插了U盘之后获取的硬盘号会变。在网上找到一个方法,可以识别系统盘的硬盘ID。分享给大家。下面是代码:
public static string GetSystemDiskNo()
{
ManagementClass cimObject = new ManagementClass("Win32_PhysicalMedia");
ManagementObjectCollection moc = cimObject.GetInstances();
Dictionary<string, string> dict = new Dictionary<string, string>();
foreach (ManagementObject mo in moc)
{
string tag = mo.Properties["Tag"].Value.ToString().ToLower().Trim();
string hdId = (string)mo.Properties["SerialNumber"].Value ?? string.Empty;
hdId = hdId.Trim();
dict.Add(tag, hdId);
}
cimObject = new ManagementClass("Win32_OperatingSystem");
moc = cimObject.GetInstances();
string currentSysRunDisk = string.Empty;
foreach (ManagementObject mo in moc)
{
currentSysRunDisk = Regex.Match(mo.Properties["Name"].Value.ToString().ToLower(), @"harddisk\d+").Value;
}
var results = dict.Where(x => Regex.IsMatch(x.Key, @"physicaldrive" + Regex.Match(currentSysRunDisk, @"\d+$").Value));
if (results.Any()) return results.ElementAt(0).Value;
return "";
}
转自: http://bbs.csdn.net/topics/392006462