千家信息网

如何实现C#启动Windows服务及关闭

发表于:2025-02-04 作者:千家信息网编辑
千家信息网最后更新 2025年02月04日,如何实现C#启动Windows服务及关闭,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。C#启动Windows服务及关闭实例实现的步骤和使
千家信息网最后更新 2025年02月04日如何实现C#启动Windows服务及关闭

如何实现C#启动Windows服务及关闭,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

C#启动Windows服务及关闭实例实现的步骤和使用调用的类是什么呢?让我们来看看具体的实现:

C# 控制Windows服务的启动与关闭

// ......    using System.ServiceProcess;   // ......   ///   /// Restart windows service  ///   ///   ///the windows service display name  ///  If the restart successfully  ///return true else return false  public static bool RestartWindowsService(string serviceName)  {      bool bResult = false;      try     {  try {  //C#启动Windows服务及关闭    StopWindowsService(serviceName);      Thread.Sleep(1000);  }  catch (Exception ex)  {      StartWindowsService(serviceName);      Thread.Sleep(1000);      StopWindowsService(serviceName);      Thread.Sleep(1000);      Console.WriteLine(ex.Message);  }  try {      StartWindowsService(serviceName);      Thread.Sleep(1000);  }  catch (Exception ex)  //C#启动Windows服务及关闭{      StopWindowsService(serviceName);      Thread.Sleep(1000);      StartWindowsService(serviceName);      Thread.Sleep(1000);      Console.WriteLine(ex.Message);  }  bResult = true;      }      catch (Exception ex)      {  bResult = false;  throw ex;      }      return bResult;  }   //C#启动Windows服务及关闭///   /// Start windows service  ///   ///   ///the windows service display name  /// If the start successfully   ///return true else return false  public static bool StopWindowsService(string serviceName)  {      ServiceController[] scs = ServiceController.GetServices();      bool bResult = false;      foreach (ServiceController sc in scs)      {  if (sc.DisplayName == serviceName)  {      try     {  sc.WaitForStatus(ServiceControllerStatus.Running,   TimeSpan.FromSeconds(30));  sc.Stop();  bResult = true;      }      catch (Exception ex)      {  bResult = false;  throw ex;      }  }      }      return bResult;  }   //C#启动Windows服务及关闭///   /// Stop windows service  ///   /// the windows  ///service display name  /// If the stop successfully   ///return true else return false  public static bool StartWindowsService(  string serviceName)  {      ServiceController[] scs   = ServiceController.GetServices();      bool bResult = false;      foreach (ServiceController sc in scs)      {  if (sc.DisplayName == serviceName)  {      try     {  sc.WaitForStatus(ServiceControllerStatus.Stopped,   TimeSpan.FromSeconds(30));  sc.Start();  bResult = true;      }      catch (Exception ex)      {  bResult = false;  throw ex;      }  }  //C#启动Windows服务及关闭    }      return bResult;  }

C#启动Windows服务及关闭具体实现就向你介绍到这里,希望对你了解和学习C#启动Windows服务及关闭有所帮助。

看完上述内容,你们掌握如何实现C#启动Windows服务及关闭的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

0