ProcessStarter.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Azylee.Core.DataUtils.StringUtils;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Security;
  8. using System.Text;
  9. namespace Azylee.Core.ProcessUtils
  10. {
  11. /// <summary>
  12. /// 进程启动工具
  13. /// </summary>
  14. public static class ProcessStarter
  15. {
  16. /// <summary>
  17. /// 创建进程
  18. /// </summary>
  19. /// <returns></returns>
  20. public static Process NewProcess(string exe, string args = "", string domain = "", string username = "", string password = "")
  21. {
  22. ProcessStartInfo startInfo = new ProcessStartInfo();
  23. if (Str.Ok(domain)) startInfo.Domain = domain;
  24. if (Str.Ok(username)) startInfo.UserName = username;
  25. if (Str.Ok(password)) startInfo.Password = ConvertToSecureString(password);
  26. startInfo.FileName = exe;
  27. startInfo.Arguments = args;
  28. startInfo.RedirectStandardInput = true;
  29. startInfo.RedirectStandardOutput = true;
  30. startInfo.RedirectStandardError = true;
  31. startInfo.UseShellExecute = false;
  32. startInfo.CreateNoWindow = true;
  33. startInfo.Verb = "RunAs";
  34. startInfo.WindowStyle = ProcessWindowStyle.Hidden;
  35. Process process = new Process();
  36. process.StartInfo = startInfo;
  37. return process;
  38. }
  39. /// <summary>
  40. /// 带权限运行的密码保密文本转换
  41. /// </summary>
  42. /// <param name="password"></param>
  43. /// <returns></returns>
  44. public static SecureString ConvertToSecureString(this string password)
  45. {
  46. try
  47. {
  48. if (password != null)
  49. {
  50. unsafe
  51. {
  52. fixed (char* passwordChars = password)
  53. {
  54. var securePassword = new SecureString(passwordChars, password.Length);
  55. securePassword.MakeReadOnly();
  56. return securePassword;
  57. }
  58. }
  59. }
  60. }
  61. catch { }
  62. return null;
  63. }
  64. /// <summary>
  65. /// 开始运行
  66. /// </summary>
  67. /// <param name="process"></param>
  68. /// <param name="output"></param>
  69. public static void Execute(Process process, Action<string> output)
  70. {
  71. StreamReader reader = null;
  72. try
  73. {
  74. process.Start();
  75. process.StandardInput.AutoFlush = true;
  76. reader = process.StandardOutput;
  77. do
  78. {
  79. string line = reader.ReadLine();
  80. output?.Invoke(line);
  81. } while (!reader.EndOfStream);
  82. process.WaitForExit();
  83. process.Close();
  84. }
  85. catch { }
  86. }
  87. }
  88. }