在C#中,我试图从Win32_Product的实例中获取一些属性,但我似乎有一个错误说“对象引用没有设置为对象的实例。”
这是代码:
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;
}
}
到达
时会出现异常p.installLocation = package["InstallLocation"].ToString();
另外,如果我尝试做的话,我会得到一个
p.installLocation = package["InstallDate2"].ToString();
如果我要求InstallDate,它可以正常工作。
(我正在使用Windows 7旗舰版x64)
答案 0 :(得分:1)
InstallLocation
为null
。
答案 1 :(得分:1)
基于跑步
gwmi -Class Win32_Product -Property Name,InstallLocation,InstallDate | ft Name,InstallLocation,InstallDate
在PowerShell中,似乎InstallLocation
在许多情况下为空。用检查null替换问题行应解决问题。