Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stop a Windows Service from code

Status
Not open for further replies.

123qweasdzc

Programmer
Sep 27, 2005
20
PT
Hello again :).

I have another problem regarding Windows Services. I want that the Windows Service can stop it self after doing some work. How is this possible? I tried to call the OnStop method, but it does not work as I aspected...

Regards,

Ricardo
 
Yes if you are using Windows XP or 2003 there is a command line tool called SC. (This is available on the windows 2000 Resource CD as well).

This tool will allow you to start/stop/query a service on a local or remote machine.

The syntax for the tool is
Code:
sc action service
example
Code:
sc stop mssqlserver

if your c# code you do this:
Code:
using System;
using System.Diagnostics;
private static void ControlService()
{
	ProcessStartInfo psi = new ProcessStartInfo();
	Process pro = new Process();
	psi.FileName = "SC.exe";
	psi.Arguments = Action + " " + ServiceName;
	psi.UseShellExecute = false;  
	pro.StartInfo = psi;
	pro.Start();
}

Give that a shot and see if that works. If you need to do this against a remote machine then psi.Arguments would look like this "\\MachineName start mssqlserver"

Ralph
 
Hello Ralph,

thanks for your tip but is precisely what I did yesterday. But I was wondering if it could be a way to stop the service without using SC or Net Stop. Is there any method we can call?
 
Let's assume the name of your service is MYSERVICE.
After doing some work, you can stop your service by executing:

ServiceController myServiceController = new ServiceController( "MYSERVICE");
myServiceController.Stop();

(Code is tripped of error checking and exception management).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top