Andrei S
Andrei S

Reputation: 6516

Win32_Product InstallLocation (error)

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)

Upvotes: 0

Views: 1098

Answers (2)

Richard
Richard

Reputation: 109130

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.

Upvotes: 1

SLaks
SLaks

Reputation: 887867

InstallLocation for that package is null.

Upvotes: 1

Related Questions