ServiceInstallUtil.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.IO;
  2. using System.Runtime.Versioning;
  3. using static PInvoke.AdvApi32;
  4. namespace FastGithub.DomainResolve
  5. {
  6. public static class ServiceInstallUtil
  7. {
  8. /// <summary>
  9. /// 安装并启动服务
  10. /// </summary>
  11. /// <param name="serviceName"></param>
  12. /// <param name="binaryPath"></param>
  13. /// <param name="startType"></param>
  14. /// <returns></returns>
  15. [SupportedOSPlatform("windows")]
  16. public static bool InstallAndStartService(string serviceName, string binaryPath, ServiceStartType startType = ServiceStartType.SERVICE_AUTO_START)
  17. {
  18. using var hSCManager = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);
  19. if (hSCManager.IsInvalid == true)
  20. {
  21. return false;
  22. }
  23. var hService = OpenService(hSCManager, serviceName, ServiceAccess.SERVICE_ALL_ACCESS);
  24. if (hService.IsInvalid == true)
  25. {
  26. hService = CreateService(
  27. hSCManager,
  28. serviceName,
  29. serviceName,
  30. ServiceAccess.SERVICE_ALL_ACCESS,
  31. ServiceType.SERVICE_WIN32_OWN_PROCESS,
  32. startType,
  33. ServiceErrorControl.SERVICE_ERROR_NORMAL,
  34. Path.GetFullPath(binaryPath),
  35. lpLoadOrderGroup: null,
  36. lpdwTagId: 0,
  37. lpDependencies: null,
  38. lpServiceStartName: null,
  39. lpPassword: null);
  40. }
  41. if (hService.IsInvalid == true)
  42. {
  43. return false;
  44. }
  45. using (hService)
  46. {
  47. return StartService(hService, 0, null);
  48. }
  49. }
  50. /// <summary>
  51. /// 停止并删除服务
  52. /// </summary>
  53. /// <param name="serviceName"></param>
  54. /// <returns></returns>
  55. [SupportedOSPlatform("windows")]
  56. public static bool StopAndDeleteService(string serviceName)
  57. {
  58. using var hSCManager = OpenSCManager(null, null, ServiceManagerAccess.SC_MANAGER_ALL_ACCESS);
  59. if (hSCManager.IsInvalid == true)
  60. {
  61. return false;
  62. }
  63. using var hService = OpenService(hSCManager, serviceName, ServiceAccess.SERVICE_ALL_ACCESS);
  64. if (hService.IsInvalid == true)
  65. {
  66. return true;
  67. }
  68. var status = new SERVICE_STATUS();
  69. if (QueryServiceStatus(hService, ref status) == true)
  70. {
  71. if (status.dwCurrentState != ServiceState.SERVICE_STOP_PENDING &&
  72. status.dwCurrentState != ServiceState.SERVICE_STOPPED)
  73. {
  74. ControlService(hService, ServiceControl.SERVICE_CONTROL_STOP, ref status);
  75. }
  76. }
  77. return DeleteService(hService);
  78. }
  79. }
  80. }