CMDServiceTool.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Azylee.Core.DataUtils.CollectionUtils;
  2. using Azylee.Core.DataUtils.StringUtils;
  3. using Azylee.Core.WindowsUtils.AdminUtils;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. namespace Azylee.Core.WindowsUtils.CMDUtils
  9. {
  10. /// <summary>
  11. /// CMD 系统服务工具类
  12. /// </summary>
  13. public static class CMDServiceTool
  14. {
  15. /// <summary>
  16. /// 安装服务(安装、运行、设置自启,一条龙服务)
  17. /// </summary>
  18. /// <param name="name">服务名</param>
  19. /// <param name="path">应用程序路径</param>
  20. /// <param name="account">运行账户信息</param>
  21. /// <returns></returns>
  22. public static bool Install(string name, string path, WindowsAccountModel account = null)
  23. {
  24. try
  25. {
  26. List<string> createResult = CMDProcessTool.Execute($"sc create {name} binPath= \"{path}\"", account);
  27. List<string> startResult = CMDProcessTool.Execute($"net start {name}", account);
  28. List<string> configResult = CMDProcessTool.Execute($"sc config {name} start= AUTO", account);
  29. if (Ls.Ok(createResult))
  30. {
  31. return createResult.Any(x => x.Contains("成功") || x.Contains("服务已存在"));
  32. }
  33. return false;
  34. }
  35. catch { return false; }
  36. }
  37. /// <summary>
  38. /// 卸载服务(关闭、删除,一条龙服务)
  39. /// </summary>
  40. /// <param name="name"></param>
  41. /// <param name="account">运行账户信息</param>
  42. public static bool Uninstall(string name, WindowsAccountModel account = null)
  43. {
  44. try
  45. {
  46. List<string> stopResult = CMDProcessTool.Execute($"sc stop {name}", account);
  47. List<string> deleteResult = CMDProcessTool.Execute($"sc delete {name}", account);
  48. List<string> queryResult = CMDProcessTool.Execute($"sc query {name}");
  49. if (Ls.Ok(queryResult))
  50. {
  51. return queryResult.Any(x => x.Contains("失败") || x.Contains("1060") || x.Contains("服务未安装"));
  52. }
  53. return false;
  54. }
  55. catch { return false; }
  56. }
  57. }
  58. }