C# - Set status of a Windows Service

  • 0 Replies
  • 146 Views

0 Members and 1 Guest are viewing this topic.

Offline Omega

    *
  • The Boss (Admin)
  • Black Hat Sec Member
  • Telegram: @BLACKHATSEC_FORUM
  • Posts: 190
  • Popularity: +1/-0
  • God of Malware
    • View Profile
    • Awards
« on: March 14, 2022, 09:21:48 AM »
C# - Set status of a Windows Service

Code
/// <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;
    }
}
  • Discord: BLACK HAT SEC#5222
  • [+]
  • [-]

  •