1.通过访问 Win32_DiskDrive 来获取:
1.1.直接 wmi 的方式:
public static List<HardDrive> get_serial_number()
{
//var hDid = string.Empty;
List<HardDrive> list = new List<HardDrive>();
ManagementObjectSearcher moSearcher = new
ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject wmi_HD in moSearcher.Get())
{
HardDrive hd = new HardDrive(); // User Defined Class
hd.Model = wmi_HD["Model"].ToString(); //Model Number
hd.Type = wmi_HD["InterfaceType"].ToString(); //Interface Type
hd.SerialNo = wmi_HD["SerialNumber"].ToString(); //Serial Number
list.Add(hd);
}
return list;
}
1.2.通过执行 cmd 命令的方式:
string cm1 = "wmic diskdrive get SerialNumber | more +1";
List<string> list1 = ExecuteCommand(cm1);
2.通过访问 Win32_PhysicalMedia 来获取:
2.1.直接 wmi 的方式:
public static List<string> get_physical_media_serial_number()
{
List<string> list = new List<string>();
ManagementObjectSearcher searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
foreach (ManagementObject wmi_HD in searcher.Get())
{
// get the hardware serial no.
if (wmi_HD["SerialNumber"] != null)
{
list.Add(wmi_HD["SerialNumber"].ToString());
}
}
return list;
}
2.2.通过执行 cmd 命令的方式:
string cm2 = "WMIC path win32_physicalmedia get serialnumber | more +1";
List<string> list2 = ExecuteCommand(cm2);
上述中使用到的 ExecuteCommand() 方法:
public static List<string> ExecuteCommand(object command)
{
try
{
List<string> list = new List<string>();
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
//string result = proc.StandardOutput.ReadToEnd();
StreamReader sr = proc.StandardOutput;//获取返回值
string line = "";
int num = 1;
while ((line = sr.ReadLine()) != null)
{
if (line != "")
{
//Console.WriteLine(line + " " + num++);
list.Add(line.Trim());
}
}
//return result;
return list;
}
catch (Exception)
{
// Log the exception
return null;
}
}
参考:
https://community.spiceworks.com/topic/671307-retrieving-hard-drive-serial-number-via-wmic
https://www.cnblogs.com/tommy-huang/p/10682660.html
How To Get The Serial Number Of Hard Drive By C#
http://netcode.ru/dotnet/?artID=7284