tags:

views:

32

answers:

2

in C#, i'm trying to get some properties from the instances of Win32_Product, but i seem to have an error saying "Object reference not set to an instance of an object."

here's the code:

class Package {
 public string productName;
 public string installDate;
 public string installLocation;
}

class InstalledPackages
{
    public static List<Package> get()
    {
        List<Package> packages = new List<Package>();
        string query = "SELECT * FROM Win32_Product";
        ManagementScope oMs = new ManagementScope();
        ObjectQuery oQuery = new ObjectQuery(query);
        ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
        ManagementObjectCollection installedPackages = oSearcher.Get();
        foreach (ManagementObject package in installedPackages)
        {
            Package p = new Package();
            p.productName = package["Name"].ToString();
            p.installLocation = package["InstallLocation"].ToString();
            p.installDate = package["InstallDate"].ToString();
            packages.Add(p);
        }
        return packages;
    }
}

the exception appears when it gets to

p.installLocation = package["InstallLocation"].ToString();

also, i get one if i try to do

p.installLocation = package["InstallDate2"].ToString();

if i'm asking for InstallDate it works.

(i'm using Windows 7 Ultimate x64)

+1  A: 

InstallLocation for that package is null.

SLaks
+1  A: 

Based on running

gwmi -Class Win32_Product -Property Name,InstallLocation,InstallDate | ft Name,InstallLocation,InstallDate

in PowerShell, it appears that InstallLocation is null in many cases. Replacing the problem line with a check for null should fix the problem.

Richard