Click here to Skip to main content
15,867,895 members
Articles / Programming Languages / C#
Article

Using the ServiceController in C# to stop and start a service

Rate me:
Please Sign up or sign in to vote.
4.24/5 (39 votes)
15 Dec 2008CPOL1 min read 216.9K   3.3K   48   25
Using the ServiceController in C# to stop and start a service.

Introduction

Have you ever searched for something small on the Internet, only to find it blown up and confusing? If so, you are like me. Below, I have listed how to use the ServiceController to control installed services. After understanding the code below, you will be able to start, stop, and get the status of a service.

Using the code

The first thing you need to do is, make a reference to System.ServiceProcess in the Solution Explorer of Visual Studio. Some of the veterans out there are probably asking why I am putting these pictures in here. The reason: it is for newbies like me who are not that familiar with adding namespaces and components.

AddReference.jpg

Add_ServiceProcess.jpg

You will see that I added what I call [QUICK CODE]. This is for those who know what they are doing, or if you are like me and you are impatient. I stripped out most comments, and it doesn't display any thing.

The larger section of code is what I use in the downloadable content. It is a console application that checks the status of the ImapiService and performs the opposite operation that it is already doing. Meaning, if the service is stopped, then I start it. If it is running, I stop it.

Once again, this is a very basic description of the ServiceController class. I hope this helps.

C#
//[QUICK CODE] FOR THE IMPATIENT
using System;
using System.Collections.Generic;
using System.Text;
// ADD "using System.ServiceProcess;" after you add the 
// Reference to the System.ServiceProcess in the solution Explorer
using System.ServiceProcess;
namespace Using_ServiceController{
    class Program{
        static void Main(string[] args){
            ServiceController myService = new ServiceController();
            myService.ServiceName = "ImapiService";
            string svcStatus = myService.Status.ToString();
                if (svcStatus == "Running"){
                    myService.Stop();
                }else if(svcStatus == "Stopped"){
                    myService.Start();
                }else{
                    myService.Stop();
                }
        }
    }
}

The complete code is here:

C#
using System;
using System.Collections.Generic;
using System.Text;
// ADD "using System.ServiceProcess;" after you add the 
// Reference to the System.ServiceProcess in the solution Explorer
using System.ServiceProcess;
namespace Using_ServiceController
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an Instance of ServiceController
            ServiceController myService = new ServiceController();
            // Define the name of your service here. 
            // I am using the 'ImapiService' for this example
            // because everyone should have this service
            // After this point, myService is now refering to "ImapiService"
            myService.ServiceName = "ImapiService";
            // Get the status of myService
            // Possible Status Returns: { StartPending, Running, PausePending, Paused, 
            //          StopPending, Stopped, ContinuePending }
            // For more info on Service Status,
            // go to: http://msdn.microsoft.com/en-us/library/
            //             system.serviceprocess.servicecontrollerstatus.aspx
            string svcStatus = myService.Status.ToString();
            if (svcStatus == "Running")
            {
                Console.WriteLine(myService.ServiceName + " is in a " + 
                                  svcStatus + "State");
                Console.WriteLine("Attempting to Stop!");
                myService.Stop();   // STOP the service if it is already Running
                // This next block is for example only to show you the states 
                // that the service is going through when it is stopping
                string svcStatusWas = "";   // This is used for this example only
                while (svcStatus != "Stopped")
                {
                    svcStatusWas = svcStatus;
                    myService.Refresh();
                    // REMEMBER: svcStatus was SET TO myService.Status.ToString above. 
                    // Use the Refresh() Method to refresh the value of myService.Status and 
                    // reassign it to svcStatus

                    svcStatus = myService.Status.ToString();
                }
                Console.WriteLine("Service Stopped!!");
            }
            else if (svcStatus == "Stopped")
            {
                Console.WriteLine(myService.ServiceName + 
                        " is in a " + svcStatus + "State");
                Console.WriteLine("Attempting to Start!");
                // START the service if it is already Stopped
                myService.Start();
                // This is used for this example only
                string svcStatusWas = "";
                while (svcStatus != "Running")
                {
                    if (svcStatus != svcStatusWas)
                    // Check to see if the Staus is the same as it was before
                    {
                        Console.WriteLine("Status: " + svcStatus);
                    }
                    svcStatusWas = svcStatus;
                    myService.Refresh();
                    svcStatus = myService.Status.ToString();
                }
                Console.WriteLine("Service Started!!");
            }
            else
            {
                // STOP the service if it is in any other state
                myService.Stop();
                Console.WriteLine("Status: " + svcStatus);
                while (svcStatus != "Stopped")
                {
                    myService.Refresh();
                    svcStatus = myService.Status.ToString();
                }
                Console.WriteLine("Service Stopped!!");
            }
            // Notification that the program is going into a sleep state
            Console.WriteLine("----Sleeping----");
            // This is a way to pause your program. This is set to 30 seconds.
            System.Threading.Thread.Sleep(30000);
        }
    }
}

Points of interest

For more information on the ServiceController class, check out MSDN.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Daystar Television Network
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionconnecting remote Pin
bharatwaj vanamamalai30-Apr-15 4:32
bharatwaj vanamamalai30-Apr-15 4:32 
Questionenums use like enums Pin
Hadi Zaker21-Dec-14 6:04
Hadi Zaker21-Dec-14 6:04 
GeneralMy vote of 1 Pin
Adam Adair10-Jun-14 6:02
Adam Adair10-Jun-14 6:02 
QuestionOperating(Start/Stop) on a Windows Service that resides on Remote Machine Pin
GoofyGoof24-Apr-14 6:42
GoofyGoof24-Apr-14 6:42 
SuggestionRe: Operating(Start/Stop) on a Windows Service that resides on Remote Machine Pin
Member 1153844018-Jul-17 2:50
Member 1153844018-Jul-17 2:50 
QuestionGood Stuff Pin
Jinesh Parekh27-Feb-14 20:50
Jinesh Parekh27-Feb-14 20:50 
QuestionRe: Good Stuff Pin
GoofyGoof24-Apr-14 6:39
GoofyGoof24-Apr-14 6:39 
QuestionService.Stop() Pin
Ashaar23-Sep-13 5:59
Ashaar23-Sep-13 5:59 
AnswerRe: Service.Stop() Pin
omar_chavez1-Dec-15 14:51
omar_chavez1-Dec-15 14:51 
GeneralGreat Dude Pin
Aman99331-Jul-13 1:13
Aman99331-Jul-13 1:13 
GeneralMy vote of 5 Pin
VEMS23-Jul-13 8:32
VEMS23-Jul-13 8:32 
GeneralMy vote of 4 Pin
J.Starkl28-Feb-13 23:53
J.Starkl28-Feb-13 23:53 
Useful
GeneralMy vote of 5 Pin
Lupit13-Jan-13 22:36
Lupit13-Jan-13 22:36 
GeneralAppreciation Pin
sampath.pandu0077-Jan-13 23:11
sampath.pandu0077-Jan-13 23:11 
GeneralVery useful! Pin
nbk111119-Sep-12 9:19
nbk111119-Sep-12 9:19 
GeneralMy vote of 4 Pin
Menon Santosh14-Oct-11 21:26
professionalMenon Santosh14-Oct-11 21:26 
GeneralMy vote of 3 Pin
vegeta4ss9-Nov-10 8:13
vegeta4ss9-Nov-10 8:13 
GeneralNice and Clear Pin
redware.com15-Jan-10 4:28
redware.com15-Jan-10 4:28 
GeneralServiceControllerStatus enumeration PinPopular
guttley1420-Jul-09 22:34
guttley1420-Jul-09 22:34 
GeneralMy vote of 1 Pin
mrmvy31-Dec-08 6:15
mrmvy31-Dec-08 6:15 
GeneralRe: My vote of 1 Pin
thechrisberry30-Aug-13 6:46
thechrisberry30-Aug-13 6:46 
GeneralExcellent Pin
ArunkumarSundaravelu23-Dec-08 23:48
ArunkumarSundaravelu23-Dec-08 23:48 
GeneralMy vote of 2 Pin
Michael B. Hansen15-Dec-08 23:39
Michael B. Hansen15-Dec-08 23:39 
GeneralExcellent Pin
Cam Birch15-Dec-08 6:59
Cam Birch15-Dec-08 6:59 
GeneralGood Example Pin
Donsw15-Dec-08 5:27
Donsw15-Dec-08 5:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.