Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 15 Dec 2008
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
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 1 PinmemberAdam Adair10-Jun-14 6:02 
QuestionOperating(Start/Stop) on a Windows Service that resides on Remote Machine PinmemberGoofyGoof24-Apr-14 6:42 
QuestionGood Stuff PinmemberJinesh Parekh27-Feb-14 20:50 
QuestionRe: Good Stuff PinmemberGoofyGoof24-Apr-14 6:39 
QuestionService.Stop() PinmemberAshaar23-Sep-13 5:59 
GeneralGreat Dude PinmemberAman99331-Jul-13 1:13 
GeneralMy vote of 5 PinmemberVEMS23-Jul-13 8:32 
GeneralMy vote of 4 PinmemberJ.Starkl28-Feb-13 23:53 
GeneralMy vote of 5 PinmemberLupit13-Jan-13 22:36 
GeneralAppreciation Pinmembersampath.pandu0077-Jan-13 23:11 
GeneralVery useful! PinmemberMember 877883019-Sep-12 9:19 
GeneralMy vote of 4 PinmemberMenon Santosh14-Oct-11 21:26 
GeneralMy vote of 3 Pinmembervegeta4ss9-Nov-10 8:13 
GeneralNice and Clear Pinmemberredware.com15-Jan-10 4:28 
GeneralServiceControllerStatus enumeration Pinmemberguttley1420-Jul-09 22:34 
GeneralMy vote of 1 Pinmembermrmvy31-Dec-08 6:15 
GeneralRe: My vote of 1 Pinmemberthechrisberry30-Aug-13 6:46 
GeneralExcellent PinmemberArunkumarSundaravelu23-Dec-08 23:48 
GeneralMy vote of 2 PinmemberMichael B. Hansen15-Dec-08 23:39 
GeneralExcellent PinmemberCam Birch15-Dec-08 6:59 
GeneralGood Example PinmemberDonsw15-Dec-08 5:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web02 | 2.8.140916.1 | Last Updated 15 Dec 2008
Article Copyright 2008 by MrPlentl
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid