本文介绍了Win32_Product InstallLocation(错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 C# 中,我试图从 Win32_Product 的实例中获取一些属性,但我似乎有一个错误提示对象引用未设置到对象的实例."
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."
代码如下:
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();
此外,如果我尝试这样做,我会得到一个
also, i get one if i try to do
p.installLocation = package["InstallDate2"].ToString();
如果我要求 InstallDate 它可以工作.
if i'm asking for InstallDate it works.
(我使用的是 Windows 7 Ultimate x64)
(i'm using Windows 7 Ultimate x64)
推荐答案
基于运行
gwmi -Class Win32_Product -Property Name,InstallLocation,InstallDate | ft Name,InstallLocation,InstallDate
在 PowerShell 中,InstallLocation
在许多情况下似乎为空.用空检查替换问题行应该可以解决问题.
in PowerShell, it appears that InstallLocation
is null in many cases. Replacing the problem line with a check for null should fix the problem.
这篇关于Win32_Product InstallLocation(错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!