【求助】用ManagementScope类连接远程的WMI发生错误
主要情况:在windows应用程序中都是可以正常运行,但是打包成服务后就发生如下错误~代码如下:
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = userName;
connectionOptions.Password = password;
ManagementScope managementScope = new ManagementScope("\\\\" + host + "\\root\\cimv2", connectionOptions);
try
{
managementScope.Connect();--此处发生错误
}
catch
{
}
return managementScope.IsConnected;
抛出的异常如下:
连接到远程计算机错误!System.UnauthorizedAccessException: 拒绝访问。 (异常来自 HRESULT:0x80070005 (E_ACCESSDENIED))
在 System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
在 System.Management.ManagementScope.InitializeGuts(Object o)
在 System.Management.ManagementScope.Initialize()
在 System.Management.ManagementScope.Connect() --------------------编程问答-------------------- 顶个 --------------------编程问答-------------------- 没人来,自己顶个先 --------------------编程问答-------------------- UnauthorizedAccessException
很显示是你没有足够的权限。 --------------------编程问答-------------------- 你可以参考一下我的代码:
--------------------编程问答-------------------- 本地不用设置 用户名跟密码
ConnectionOptions connection_wmi = new ConnectionOptions();
connection_wmi.Username = "administrator";
connection_wmi.Password = "123";
connection_wmi.Authority = "ntlmdomain:DOMAIN";
ManagementScope scope = new ManagementScope("\\\\10.20.18.35\\root\\CIMV2", connection_wmi);
scope.Connect();
ObjectQuery oq = new ObjectQuery(string.Format("SELECT * FROM Win32_Process where ProcessId = {0}", iPid));
ManagementObjectSearcher query = new ManagementObjectSearcher(_scope, oq);
foreach (ManagementObject queryObj in query.Get())
queryObj.InvokeMethod("Terminate", null);
你把用户名跟密码的哪两行代码注释掉就可以 --------------------编程问答-------------------- 我表示和你碰到的问题一样,本地cosole没问题,打成service注册到服务管理器再用就出问题,也是
UnauthorizedAccessException
后来发现,这个是因为打包成服务的时候权限不对,服务的account应该是NetworkService,而不是localSystem
补充:.NET技术 , C#