ソースを参照

CMD进程操作增加读取Error流

yuzhengyang 6 年 前
コミット
bd61e25edf

+ 1 - 1
Azylee.Utils/Azylee.Core/Properties/AssemblyInfo.cs

@@ -32,4 +32,4 @@ using System.Runtime.InteropServices;
 // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
 //通过使用 "*",如下所示:
 // [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.8")]
+[assembly: AssemblyVersion("1.0.0.9")]

+ 28 - 7
Azylee.Utils/Azylee.Core/WindowsUtils/CMDUtils/CMDProcessTool.cs

@@ -16,6 +16,9 @@ using System.Threading.Tasks;
 
 namespace Azylee.Core.WindowsUtils.CMDUtils
 {
+    /// <summary>
+    /// CMD进程启动工具
+    /// </summary>
     public class CMDProcessTool
     {
         /// <summary>
@@ -51,8 +54,9 @@ namespace Azylee.Core.WindowsUtils.CMDUtils
         /// <param name="output">输出动作</param>
         public static void Execute(string cmd, Action<string> output, WindowsAccountModel account = null)
         {
-            StreamReader reader = null;
             Process process = null;
+            StreamReader outReader = null;
+            StreamReader errReader = null;
             try
             {
                 process = GetProcess(account: account);
@@ -60,12 +64,13 @@ namespace Azylee.Core.WindowsUtils.CMDUtils
                 process.StandardInput.AutoFlush = true;
                 process.StandardInput.WriteLine(cmd);
                 process.StandardInput.WriteLine("exit");
-                reader = process.StandardOutput;
-                do
-                {
-                    string line = reader.ReadLine();
-                    output?.Invoke(line);
-                } while (!reader.EndOfStream);
+
+                outReader = process.StandardOutput;
+                errReader = process.StandardError;
+
+                ReaderAction(outReader, output);
+                ReaderAction(errReader, output);
+
                 process.WaitForExit();
                 process.Close();
             }
@@ -105,5 +110,21 @@ namespace Azylee.Core.WindowsUtils.CMDUtils
             }
             return result;
         }
+        private static void ReaderAction(StreamReader reader, Action<string> output)
+        {
+            try
+            {
+                Task.Factory.StartNew(() =>
+                {
+                    do
+                    {
+                        string line = reader.ReadLine();
+                        output?.Invoke(line);
+                    } while (!reader.EndOfStream);
+                    string s = "reader process is end";
+                });
+            }
+            catch { }
+        }
     }
 }