简体   繁体   中英

In C# how to stop/start/check whether registered or not if the Log On As account is of non-admin user?

I have a service whose LogOnAs is not Local System.It is a different user (say test with administrative privilege).Using Normal code :doesnt work it always throws exception.

 public  bool IsServiceInstalled(String serviceName)
    {
        bool IsInstalled = false;
        // get list of Windows services
        ServiceController[] services = ServiceController.GetServices();

        // try to find service name
        foreach (ServiceController service in services)
        {
            if (service.ServiceName == serviceName)
            {
                IsInstalled = true;
                break;
            }
        }
        return IsInstalled;
    }

Any help will be greatly appreciated...

To begin with, you can simplify your logic with:

public  bool IsServiceInstalled(String aServiceName)
{
   ServiceController sc = ServiceController.GetServices()
       .FirstOrDefault(s => s.ServiceName == aServiceName);

   return (sc != null) ;
}

This uses linq to get the first matching service with the passed name (I've changed the parameter to aServiceName , the a stands for argument).

It won't solve your problem, but will be easier to read and maintain.

Does this work for you when you're logged on normally?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM