C#,WMI和Windows 7与Windows 2008通讯

C#, WMI and Windows 7 talking to Windows 2008

我已经为此花了几天的时间,但我不知道发生了什么。我的开发箱是一台Windows 7 64位计算机,我正在尝试通过WMI连接到Windows Server 2008域控制器。

我的代码非常简单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ConnectionOptions options = new ConnectionOptions();
options.Username = _username;
options.Password = _password;
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Default;          

ManagementScope scope = new ManagementScope(@"\" + _hostip + @"\
oot\\cimv2"
, options);

scope.Connect(); // this works!

ManagementEventWatcher watcher = new ManagementEventWatcher();
watcher.Scope = scope;
watcher.Query = new EventQuery(@"SELECT * FROM __InstanceCreationEvent WHERE TargetInstance ISA 'Win32_NTLogEvent' and TargetInstance.LogFile = 'Security'");

watcher.Start() // throws exception
watcher.WaitForNextEvent(); // works

我对WMI的了解有限,我无法弄清楚WaitForNextEvent()为何起作用,而Start()却不起作用。我一直得到的例外是:访问被拒绝。 (来自HRESULT的异常:0x80070005(E_ACCESSDENIED))

我已多次检查我尝试连接的域控制器是否正确设置(远程处理已启用,已启用并具有权限),就像我用来连接的用户帐户一样。

任何想法和见识将不胜感激。


尝试一下:

1
options.Authentication = AuthenticationLevel.PacketPrivacy;

我认为您很热衷于此错误,因为部分受信任的代码无法使用此成员,如文档中所述。有关更多信息,请参见使用部分受信任代码中的库。

您可以在不使用此成员的情况下接收事件。