Access resources within WMI commands in a Windows service

This is a little obscure. I’m writing a Windows service that can be controlled via WMI. I use Log4Net to log all of the service’s activities. I can see logs from the service starting up and doing its regular processing, but I can’t see logs from WMI commands.

In addition, when the WMI command tells the service to access a resource (eg. load a configuration file or walk a directory tree), the command fails. WMI error messages aren’t much help (“Not found” anybody? How about “The RPC server is unavailable.”) And with logging not working, I have to attach the debugger to see what’s happening.

Cancel impersonation

The reason for both of these problems is that the WMI user doesn’t have access to either the log file or the resource I’m trying to access. The solution, cancel impersonation:

public class CancelImpersonation : IDisposable
    private WindowsImpersonationContext _impersonationContext;

    public CancelImpersonation()
        _impersonationContext = WindowsIdentity.Impersonate(IntPtr.Zero);

    public void Dispose()

Wrap one of these in a using statement, then anything you do in the brackets is running as local system (or whatever user the service is configured to run as).

Leave a Reply

You must be logged in to post a comment.