Click here to Skip to main content
Click here to Skip to main content

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

By , 15 Dec 2008
 

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)

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberJ.Starkl28 Feb '13 - 23:53 
GeneralMy vote of 5memberLupit13 Jan '13 - 22:36 
GeneralAppreciationmembersampath.pandu0077 Jan '13 - 23:11 
GeneralVery useful!memberMember 877883019 Sep '12 - 9:19 
GeneralMy vote of 4memberMenon Santosh14 Oct '11 - 21:26 
GeneralMy vote of 3membervegeta4ss9 Nov '10 - 8:13 
GeneralNice and Clearmemberredware.com15 Jan '10 - 4:28 
GeneralServiceControllerStatus enumerationmemberguttley1420 Jul '09 - 22:34 
GeneralMy vote of 1membermrmvy31 Dec '08 - 6:15 
GeneralExcellentmemberArunkumarSundaravelu23 Dec '08 - 23:48 
GeneralMy vote of 2memberMichael B. Hansen15 Dec '08 - 23:39 
GeneralExcellentmemberCam Birch15 Dec '08 - 6:59 
GeneralGood ExamplememberDonsw15 Dec '08 - 5:27 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 15 Dec 2008
Article Copyright 2008 by MrPlentl
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid