public static string GetSerialPort()
{
return MulGetHardwareInfo(HardwareEnum.Win32_SerialPort, "Name");
}
//枚举win32 api
public enum HardwareEnum
{
Win32_SerialPort
,
Win32_SerialPortConfiguration
,
Win32_SerialPortSetting
}
public static string MulGetHardwareInfo(HardwareEnum hardType, string propKey)
{
string strs = "";
string ttt = "STMicr";
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + hardType);
var hardInfos = searcher.Get();
foreach (var hardInfo in hardInfos)
{
if (hardInfo.Properties[propKey] != null)
{
strs = hardInfo.Properties[propKey].Value.ToString();
string id = Convert.ToString(strs.Substring(0, 6));
if (id == ttt)
{
strs = Convert.ToString(strs.Substring(37, 5));
}
else
{
strs = "No Found";
}
}
}
return strs;
}
大概的意思是 从数据库里取出某字段 循环检查值的前6位是不是和STMicr相等,如果等则取某一字段。
但是这段代码没有实现上述功能,也就是说有bug:
1、strs.Substring(37, 5) ,没有这种取值方式。
2、strs = Convert.ToString(strs.Substring(37, 5));取出的字符串只存在临时变量中,下一次循环会把查询结果覆盖,除非hardInfos的元素只有一个,不然该方法返回的总是最后一个元素的相应字段,没有意义
查询电脑里所有的管理对象,比如磁盘、驱动中名字为STMicr(半导体)的某个硬件,然后取出该硬件的hardware信息。