user1438082
user1438082

Reputation: 2748

WMI query for empty property

On the WMI query below if the proptery is blank then my code errors. How can i make the code return "" when the property does not exist ? For example queryObj["Help Telephone"] is null so my code is erroring out but i want it to continue.

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('"');
}

Upvotes: 0

Views: 831

Answers (1)

Dmitry
Dmitry

Reputation: 14059

You could create a helper method:

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('"');
}

And use it as follows:

TemporarySoftware.sAssignmentType = GetNameContents(queryObj, "AssignmentType");
TemporarySoftware.sCaption = GetNameContents(queryObj, "Caption");

Upvotes: 1

Related Questions