C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

How to start and stop windows services programmatically


Posted Date: 20 Apr 2005    Resource Type: Articles    Category: .NET Framework
Author: Tony JohnMember Level: Diamond    
Rating: 1 out of 5Points: 10



Introduction



This short code snippet shows how you can start and stop windows services and also how to find the current status of any windows services.

System.ServiceProcess.ServiceController class



You can use the .NET class System.ServiceProcess.ServiceController to work with the windows services.

Include the namespace in the top of your class:

VB.NET

Imports System.ServiceProcess

C#

using System.ServiceProcess;


Create an instance of the class:
VB.NET

dim controller as new ServiceController

C#

ServiceController controller = new ServiceController();


See the following code which gets the status of the IIS Admin service. Also, you can start and stop the service using this class.

VB.NET

controller.MachineName = "."
controller.ServiceName = "IISADMIN"
dim status as string = controller.Status.ToString

' Stop the service
controller.Stop()

' Start the service
controller.Start()

C#

controller.MachineName = ".";
controller.ServiceName = "IISADMIN";
string status = controller.Status.ToString();

// Stop the service
controller.Stop();

// Start the service
controller.Start();




Responses

Author: Yuri Sho    22 Apr 2008Member Level: Bronze   Points : 0
When I try happen this error:

System.InvalidOperationException = {"Cannot stop wuauserv service on computer '.'."}

InnerException = {"The service has not been started"}

System.ComponentModel.Win32Exception = {"The service has not been started"}

ErrorCode = -2147467259

NativeErrorCode = 1062

How to correct? ThX!


Author: Vikas Kumar Singh    14 May 2008Member Level: Bronze   Points : 2
Hi,

Check for the service's startup type if disable. Keep it either Automatic or Manual.

Regards,
Vikas Singh


Author: Sunil    09 Nov 2009Member Level: Bronze   Points : 2
Here is the code with Exception handling.
private void btnStart_Click(object sender, EventArgs e)
{
ServiceController sc = new System.ServiceProcess.ServiceController(strSVCName);
try
{

if (sc.Status.Equals(ServiceControllerStatus.Paused))
{
sc.Continue();
sc.WaitForStatus(ServiceControllerStatus.Running);
btnStart.Enabled = false;
btnStop.Enabled = true;
btnPause.Enabled = true;
lblServiceStatus.Text = "Running";
}
else
{
sc.Start();
sc.WaitForStatus(ServiceControllerStatus.Running);
if (sc.Status.Equals(ServiceControllerStatus.Running))
{
btnStart.Enabled = false;
btnStop.Enabled = true;
lblServiceStatus.Text = "Running";
if (sc.CanPauseAndContinue)
btnPause.Enabled = true;
}
}

}
catch (Exception ex)
{
MessageBox.Show("Could not start " + strSVCName + " Service.\n Error : " + ex.Message.ToString());
}
finally
{
sc.Close();
}
}

private void btnStop_Click(object sender, EventArgs e)
{

ServiceController sc = new System.ServiceProcess.ServiceController(strSVCName);
try
{
sc.Stop();
sc.WaitForStatus(ServiceControllerStatus.Stopped);


if (sc.Status.Equals(ServiceControllerStatus.Stopped))
{
btnStart.Enabled = true;
btnStop.Enabled = false;
btnPause.Enabled = false;
lblServiceStatus.Text = "Stopped";
}
}
catch (Exception ex)
{
MessageBox.Show("Could not stop " + strSVCName + " Service.\n Error : " + ex.Message.ToString());
}
finally
{
sc.Close();
}
}


Author: MathiasE    20 Nov 2009Member Level: Bronze   Points : 2
Hi,
Thanks for this great post!
I tried it and it worked fine on a Windows XP system.

But on Windows 7 I get an error:
"Service [ServiceName] cannot be opened on computer [MachineName]"

The service is a local service.

With "sc stop [ServiceName]" at the command-prompt I got:
[SC] OpenService Error 5: Access denied
Navigating through the options of services.msc, wmimgmt.msc, gpedit.msc I couldn't find the specific option to get this access.
How is it possible to control that and to start and stop a service with the ServiceController-Class?

Thanks for help!
MathiasE


Author: Sunil    20 Nov 2009Member Level: Bronze   Points : 1
Hi,

As always Vista onwards all the os are headache for developer.
Open command run as an administrator. and then try.
it will work.

Regards,
Sunil G.


Author: Sunil    21 Nov 2009Member Level: Bronze   Points : 1
Hi,

As always Vista onwards all the os are headache for developer.
Open command run as an administrator. and then try.
it will work.

Regards,
Sunil G.


Author: MathiasE    21 Nov 2009Member Level: Bronze   Points : 1
Thanks, Sunil!
It works. But it seems no good idea, to tell users of my app to run it as administrator, since most of them aren't. (And the IT people do not want the service running permanently.) Is there no way to control a specific service access programmatically?
Regards,
MathiasE


Author: Sunil    21 Nov 2009Member Level: Bronze   Points : 1
Hi,

Just add administrator group to your application. This should work for u.

Regards,
Sunil G.


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Thanks a Lot!  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Examples of how to Calculate Different VB.NET Dates
Previous Resource: .Net Remoting Grounds up !!!
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use