在下面的WMI查询中,如果proptery为空,那么我的代码错误。当属性不存在时,如何使代码返回“”?例如queryObj [“Help Telephone”]为空,所以我的代码出错,但我希望它继续。
ManagementObjectSearcher searcherSoftware = new ManagementObjectSearcher("root\\CIMV2", "Select * from Win32_Product");
foreach (ManagementObject queryObj in searcherSoftware.Get())
{
ItemsUnderControlObject TemporarySoftware = new ItemsUnderControlObject();
TemporarySoftware.sType = "Software";
TemporarySoftware.sAssignmentType = queryObj["AssignmentType"].ToString().Split(new[] { "Name=" }, StringSplitOptions.None).Last().Trim('"'); //http://stackoverflow.com/questions/22583873/get-names-from-string-values/22583919?noredirect=1#22583919
TemporarySoftware.sCaption = queryObj["Caption"].ToString().Split(new[] { "Name=" }, StringSplitOptions.None).Last().Trim('"');
TemporarySoftware.sDescription = queryObj["Description"].ToString().Split(new[] { "Name=" }, StringSplitOptions.None).Last().Trim('"');
TemporarySoftware.sHelpLink = queryObj["HelpLink"].ToString().Split(new[] { "Name=" }, StringSplitOptions.None).Last().Trim('"');
TemporarySoftware.sHelpTelephone = queryObj["Help Telephone"].ToString().Split(new[] { "Name=" }, StringSplitOptions.None).Last().Trim('"');
}
答案 0 :(得分:1)
您可以创建辅助方法:
private static string GetNameContents(ManagementObject queryObj, string propertyName)
{
object propertyValue = queryObj[propertyName];
if (propertyValue == null)
return String.Empty;
string propertyString = propertyValue.ToString();
return propertyString.Length == 0
? String.Empty
: propertyString.Split(new[] { "Name=" }, StringSplitOptions.None).Last().Trim('"');
}
使用如下:
TemporarySoftware.sAssignmentType = GetNameContents(queryObj, "AssignmentType");
TemporarySoftware.sCaption = GetNameContents(queryObj, "Caption");