我正在尝试使用ManagementObjectSearcher
运行查询,这是我的代码:(网络核心2.1)
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * from Win32_Printer");
ManagementObjectCollection coll = searcher.Get();
在我的计算机上(Windows 10)可以正常工作,但在客户端计算机Windows Server 2012R2上却出现以下错误:
`Unhandled Exception: System.TypeInitializationException: The type initializer fo
r 'System.Management.ManagementPath' threw an exception. ---> System.TypeInitial
izationException: The type initializer for 'System.Management.WmiNetUtilsHelper'
threw an exception. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: ptr
at System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(IntPt
r ptr, Type t)
at System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer[TDele
gate](IntPtr ptr)
at System.Management.WmiNetUtilsHelper.LoadDelegate[TDelegate](TDelegate& del
egate_f, IntPtr hModule, String procName)
at System.Management.WmiNetUtilsHelper..cctor()
--- End of inner exception stack trace ---
at System.Management.MTAHelper.IsNoContextMTA()
at System.Management.MTAHelper.CreateInMTA(Type type)
at System.Management.ManagementPath.CreateWbemPath(String path)
at System.Management.ManagementPath..ctor(String path)
at System.Management.ManagementPath..cctor()
--- End of inner exception stack trace ---
at System.Management.ManagementScope._Clone(ManagementScope scope, Identifier
ChangedEventHandler handler)
at System.Management.ManagementObjectSearcher..ctor(ManagementScope scope, Ob
jectQuery query, EnumerationOptions options)`
我将其发布为win-86 exe
答案 0 :(得分:2)
似乎System.Management
需要完整的.NET Framework。此特定查询似乎仅适用于.NET Framework 4.7。我已经用4.0、4.5.2和4.7.2进行了测试,只有后者不会给我这个例外。我的C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WMINet_Utils.dll
版本是4.7.2053.0
请注意,Microsoft不鼓励使用System.Management
的新代码,而应使用Microsoft.Management.Infrastructure
。