ProcessStarter.cs 2.6 KB

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