ProcessStarter.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. private static SecureString ConvertToSecureString(this string password)
  45. {
  46. if (password == null)
  47. throw new ArgumentNullException("password");
  48. unsafe
  49. {
  50. fixed (char* passwordChars = password)
  51. {
  52. var securePassword = new SecureString(passwordChars, password.Length);
  53. securePassword.MakeReadOnly();
  54. return securePassword;
  55. }
  56. }
  57. }
  58. /// <summary>
  59. /// 开始运行
  60. /// </summary>
  61. /// <param name="process"></param>
  62. /// <param name="output"></param>
  63. public static void Execute(Process process, Action<string> output)
  64. {
  65. StreamReader reader = null;
  66. try
  67. {
  68. process.Start();
  69. process.StandardInput.AutoFlush = true;
  70. reader = process.StandardOutput;
  71. do
  72. {
  73. string line = reader.ReadLine();
  74. output?.Invoke(line);
  75. } while (!reader.EndOfStream);
  76. process.WaitForExit();
  77. process.Close();
  78. }
  79. catch { }
  80. }
  81. }
  82. }