C#調用Windows CMD命令並,返回輸出結果或錯誤信息


 1 public static string InvokeExcute(string Command)
 2 {
 3     Command = Command.Trim().TrimEnd('&') + "&exit";
 4     using (Process p = new Process())
 5     {
 6         p.StartInfo.FileName = "cmd.exe";
 7         p.StartInfo.UseShellExecute = false;        //是否使用操作系統shell啟動
 8         p.StartInfo.RedirectStandardInput = true;   //接受來自調用程序的輸入信息
 9         p.StartInfo.RedirectStandardOutput = true;  //由調用程序獲取輸出信息
10         p.StartInfo.RedirectStandardError = true;   //重定向標准錯誤輸出
11         p.StartInfo.CreateNoWindow = true;          //不顯示程序窗口
12         p.Start();//啟動程序
13         //向cmd窗口寫入命令
14         p.StandardInput.WriteLine(Command);
15         p.StandardInput.AutoFlush = true;
16         //獲取cmd窗口的輸出信息
17         StreamReader reader = p.StandardOutput;//截取輸出流
18         StreamReader error = p.StandardError;//截取錯誤信息
19         string str = reader.ReadToEnd() + error.ReadToEnd();
20         p.WaitForExit();//等待程序執行完退出進程
21         p.Close();
22         return str;
23     }
24 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM