Start/Stop/Restart a windows Service from C# with ServiceController

Hello Experts,

I want to restart the "SAVService" (Sophos Antivirus) windows service using the ServiceController class in C#.

-- I added a reference to the ServiceProcess.dll in my C# project

-- I defined the service like this:
myService.ServiceName = "SAVService";

--I can get the status of the service like this
string svcStatus = myService.Status.ToString(); //This works - Shows SAVService is "Runing"


When I try to stop the SAVService like this: myService.Stop();

I get an Exception "Cannot open SAVService on the computer" I suspect this may be a security issue. The SAVService on my computer will only start/stop using the Login "Local System" or Login/pswd "Local Service\Sophos default password"  

Does anyone know how to define the User/Password for a windows service in   ServiceController ?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Karrtik IyerSoftware ArchitectCommented:
If you plan to use Service Controller then you will have to use WMI to set the user name and password while starting the service.(WMI)
You can also use service manage command line options to invoke this command from C# code.
I would suggest if possible and feasible, you use PsService utility from Microsoft/SysInternals that provide command line arguments to pass user name and password while starting service. You can invoke this from the C# code. Please refer the link below for the examples on command line arguments to this PsService Utility.
SaxitalisAuthor Commented:
Thanks, -I'll look into SCM and PSService. I actually need to do this on remote computers in a Windows 7 work group.

Will these tools apply to remote computer service start/stop?
Karrtik IyerSoftware ArchitectCommented:
Yes PSService allows to you start/stop services on remote computer as well. Please refer example below on how that can be done.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SaxitalisAuthor Commented:
Thank you
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.