开发者

How to use ManagementEventWatcher in a windoes service?

I am trying to use ManagementEventWatcher inside a C# .NET4 windows service application. At some point in the "OnStart" method I have these lines:

string scope = "\\root\\cimv2";
string query =
  "SELECT * FROM __InstanceCreationEvent " +
  "WITHIN 1 " +
  "WHERE TargetInstance ISA 'Win32_NTLogEvent' " +
  " AND ( " +
  "      targetInstance.EventCode = '4768' " + 
  "   OR targetInstance.EventCode = '4770' " + 
  "   OR targetInstance.EventCode = '672'" + 
  "   OR targetInstance.EventCode = '674'" + 
  " )";
eventListener = new ManagementEventWatcher(scope, query);
eventListener.EventArrived += new EventArrivedEventHandler(HandleEvent);


eventListener.Start();

The eventListener.Start(); line gives an exception with the message "Access Denied". I tried to set up my service as Administrator or LOCALSYSTEM but it does not help.

I also found this documentation: http://msdn.microsoft.com/e开发者_高级运维n-us/library/aa392289(VS.85).aspx But I can not figure out how to use it in C#.

The same code works as expected if put in a WindowsForms application.

Thanks.


There is nothing inherent here that will prevent a service from providing this functionality. I actually took your code and ran it fine on my machine as a service(famous developer last words) under the localsystem account. If the account running lacks permissions to the event log, in your case, or anything else it needs it will bail. A few general tips from my all-too-frequent experience with troubleshoooting similar problems: 1. Remember that you can choose to "run as" for your windows form app to run under a different account than you happen to be logged in as. I suspect running your windows form app with the Administrator account will fail exactly as your service did. 2. Selectively using security auditing can be very help in pinpointing access problems. 3. Using Sysinternals ProcMon can often pinpoint what exactly access is being denied to. 4. To make debugging as much of your service code as possible without it running as a service use the #DEBUG as suggested in this blog post (http://jclaes.blogspot.com/2010/03/cannot-start-service-from-command-line.html)


It turns out this is a problem with Windows XP. The code fails on it, but works on any newer Windows versions, starting with Windows 2003.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜