Set status of a Windows service with C#

PsychoCoder 0 Tallied Votes 761 Views Share

C# code snippet demonstrating how to set the status of a specified Windows service. Provide the name of the service and it's value (it's an integer value described in the comments)

/// <summary>
/// method for setting the value of a Windows Service:
/// 2 => Automatic
/// 3 => Manual
/// 4 => Disabled
/// </summary>
/// <param name="serviceName">service we're looking for</param>
/// <param name="value">integer value to set the Start key to</param>
/// <returns></returns>
public bool SetWindowsServiceStatus(string serviceName,int value)
{
    try 
    {
        //open the registry key for the specified Windows Service
        Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(string.Format(@"SYSTEM\CurrentControlSet\Services\{0}", serviceName), true);

        //if exists then set the value to the desired value
        if (key != null)
        {
            /*now set the value of the Start value:
             * 2 => Automatic
             * 3 => Manual
             * 4 => Disabled
             * */
            key.SetValue("Start", value);
            return true;
        }
        else
        {
            //not found, so service isnt available or isntalled
            throw new Exception(string.Format("The Windows Service {0} could not be located or does not exist", serviceName));
        }
    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);
        return false;
    }
}