如何更快地获得 ManagementObject 的结果

问题描述 投票:0回答:1

我创建了从 Windows 操作系统收集已安装应用程序版本信息的方法。但是在将值分配给 foreach 时面临缓慢的问题。获取 ManagementObjectSearcher 结果更快。对我的要求有什么建议吗?

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Product WHERE Name=Google Chrome");

foreach (ManagementObject obj in searcher.Get()) // this part is taking too long time to process
{
    MessageBox.Show(obj["Name"] + "-----" + obj["Version"]);
};
c# winforms foreach
1个回答
0
投票

我刚刚在 Win32_Printer 类上遇到了同样的问题。我将查询更改为 ManagementPath。现在速度快多了

ConnectionOptions con = new ConnectionOptions();
con.Impersonation = ImpersonationLevel.Impersonate;
con.Authentication = AuthenticationLevel.Packet;
con.EnablePrivileges = true;
con.Username = "User";
con.Password = "Password";

ManagementScope scope = new ManagementScope($@"\\{printServer}\root\cimv2", con);
scope.Connect();

ManagementPath printerPath = new ManagementPath($"Win32_Printer.DeviceID='{PrinterName}'");
ManagementObject printer = new ManagementObject(scope, printerPath, new ObjectGetOptions());
printer.Get();

//Do whatever you want with the ManagementObject
printer.Delete();

只要您知道要查找的类的 CIM_Key,您就可以找到任何类似的对象 https://learn.microsoft.com/de-de/windows/win32/cimwin32prov/win32-printer

我想我把它留在这里,可能对某人有用!

© www.soinside.com 2019 - 2024. All rights reserved.