Click here to Skip to main content
12,634,888 members (27,333 online)
Click here to Skip to main content
Add your own
alternative version

Stats

135.6K views
2.6K downloads
48 bookmarked
Posted

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

, 15 Dec 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
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.

//[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:

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)

Share

About the Author

MrPlentl
Web Developer Daystar Television Network
United States United States
No Biography provided

You may also be interested in...

Pro
Pro

Comments and Discussions

 
Questionconnecting remote Pin
Member 1102782030-Apr-15 5:32
memberMember 1102782030-Apr-15 5:32 
Questionenums use like enums Pin
Hadi Zaker21-Dec-14 7:04
memberHadi Zaker21-Dec-14 7:04 
GeneralMy vote of 1 Pin
Adam Adair10-Jun-14 7:02
memberAdam Adair10-Jun-14 7:02 
QuestionOperating(Start/Stop) on a Windows Service that resides on Remote Machine Pin
GoofyGoof24-Apr-14 7:42
memberGoofyGoof24-Apr-14 7:42 
QuestionGood Stuff Pin
Jinesh Parekh27-Feb-14 21:50
memberJinesh Parekh27-Feb-14 21:50 
QuestionRe: Good Stuff Pin
GoofyGoof24-Apr-14 7:39
memberGoofyGoof24-Apr-14 7:39 
QuestionService.Stop() Pin
Ashaar23-Sep-13 6:59
memberAshaar23-Sep-13 6:59 
AnswerRe: Service.Stop() Pin
omar_chavez1-Dec-15 15:51
memberomar_chavez1-Dec-15 15:51 
GeneralGreat Dude Pin
Aman99331-Jul-13 2:13
memberAman99331-Jul-13 2:13 
GeneralMy vote of 5 Pin
VEMS23-Jul-13 9:32
memberVEMS23-Jul-13 9:32 
GeneralMy vote of 4 Pin
J.Starkl1-Mar-13 0:53
memberJ.Starkl1-Mar-13 0:53 
GeneralMy vote of 5 Pin
Lupit13-Jan-13 23:36
memberLupit13-Jan-13 23:36 
GeneralAppreciation Pin
sampath.pandu0078-Jan-13 0:11
membersampath.pandu0078-Jan-13 0:11 
GeneralVery useful! Pin
Member 877883019-Sep-12 10:19
memberMember 877883019-Sep-12 10:19 
GeneralMy vote of 4 Pin
Menon Santosh14-Oct-11 22:26
memberMenon Santosh14-Oct-11 22:26 
GeneralMy vote of 3 Pin
vegeta4ss9-Nov-10 9:13
membervegeta4ss9-Nov-10 9:13 
GeneralNice and Clear Pin
redware.com15-Jan-10 5:28
memberredware.com15-Jan-10 5:28 
GeneralServiceControllerStatus enumeration PinPopular
guttley1420-Jul-09 23:34
memberguttley1420-Jul-09 23:34 
GeneralMy vote of 1 Pin
mrmvy31-Dec-08 7:15
membermrmvy31-Dec-08 7:15 
GeneralRe: My vote of 1 Pin
thechrisberry30-Aug-13 7:46
memberthechrisberry30-Aug-13 7:46 
GeneralExcellent Pin
ArunkumarSundaravelu24-Dec-08 0:48
memberArunkumarSundaravelu24-Dec-08 0:48 
GeneralMy vote of 2 Pin
Michael B. Hansen16-Dec-08 0:39
memberMichael B. Hansen16-Dec-08 0:39 
GeneralExcellent Pin
Cam Birch15-Dec-08 7:59
memberCam Birch15-Dec-08 7:59 
GeneralGood Example Pin
Donsw15-Dec-08 6:27
memberDonsw15-Dec-08 6: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161208.2 | Last Updated 15 Dec 2008
Article Copyright 2008 by MrPlentl
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid