C# - Stop or start a Windows Service

  • 0 Replies
  • 153 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:24:20 AM »
C# - Stop or start a Windows Service

Code
/// <summary>
/// method to stop/start a specified Windows Service on the local machine
/// </summary>
/// <param name="serviceName">ther Windows service we want to stop/start</param>
/// <param name="start">are we stopping or starting</param>
/// <param name="args">arguments we want passed to the Windows service (optional)</param>
/// <returns></returns>
public bool HandleWindowsService(string serviceName, bool start, string[] args = null)
{
    try
    {
        using (System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController())
        {
            service.MachineName = ".";
            service.ServiceName = serviceName;

            if (DoesServiceExist(serviceName))
            {
                switch (start)
                {
                    case true:

                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                        {
                            if (args == null)
                                service.Start();
                            else
                                service.Start(args);
                        }
                        return true;
                    case false:
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                            service.Stop();
                        return true;
                    default:
                        if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
                        {
                            if (args == null)
                                service.Start();
                            else
                                service.Start(args);
                        }
                        return true;
                }
            }
            else
            {
                throw new Exception(string.Format("The service {0} could not be found", serviceName));
                return false;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

/// <summary>
/// method to determine if a Windows Service is available on the local service
/// </summary>
/// <param name="service"></param>
/// <returns></returns>
private bool DoesServiceExist(string service)
{
    System.ServiceProcess.ServiceController[] services = System.ServiceProcess.ServiceController.GetServices(".");
    return services.Any(s => s.ServiceName == service.ToLower());
}
  • Discord: BLACK HAT SEC#5222
  • [+]
  • [-]

  •