2017-10-08 236 views
0

我一直在尋找「如何從cmd獲得標準輸出」,我發現了一些教程,但沒有,是的NONE似乎工作,即時嘗試讀取所有輸出「cmd。 exe「對我來說。從cmd讀取輸出獲取錯誤

繼承人整個代碼,向下滾動的錯誤位置

public static string C(string arguments, bool b) 
    { 
     System.Diagnostics.Process process = new 
     System.Diagnostics.Process(); 
     System.Diagnostics.ProcessStartInfo startInfo = new 
     System.Diagnostics.ProcessStartInfo(); 
     startInfo.WindowStyle = 
     System.Diagnostics.ProcessWindowStyle.Hidden; 
     process.StartInfo.RedirectStandardOutput = true; 
     process.StartInfo.RedirectStandardInput = true; 
     process.StartInfo.UseShellExecute = false; 
     startInfo.FileName = "cmd.exe"; 
     startInfo.Arguments = arguments; 
     process.StartInfo = startInfo; 
     process.Start(); 

     string res = ""; 
     if (b) 
     { 
      StringBuilder q = new StringBuilder(); 
      while (!process.HasExited) 
      { 
       q.Append(process.StandardOutput.ReadToEnd()); 
      } 
      string r = q.ToString(); 
      res = r; 
     } 
     if(res == "" || res == null) 
     { 
      return "NO-RESULT"; 
     } 
     return res; 

    } 

從哪裏獲得我的錯誤(System.InvalidOperationException:「StandardOut沒有被重定向或進程尚未啓動。」)

string res = ""; 
    StringBuilder q = new StringBuilder(); 
    while (!process.HasExited) 
    { 
     q.Append(process.StandardOutput.ReadToEnd()); // Right here 
    } 
    string r = q.ToString(); 
    res = r; 
+0

您是否嘗試過[這](https://stackoverflow.com/questions/1145969/processinfo-and-redirectstandardoutput)? –

回答

0

您正在創建一個名爲ProcessStartInfostartInfo,然後process.StartInfo設置一些屬性,然後分配給startInfo基本上process.StartInfo恢復你設置公關eviously。

,你應該在startInfo設置RedirectStandardOutputRedirectStandardInputUseShellExecute

System.Diagnostics.Process process = new System.Diagnostics.Process(); 
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); 
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
startInfo.RedirectStandardOutput = true; 
startInfo.RedirectStandardInput = true; 
startInfo.UseShellExecute = false; 
startInfo.FileName = "cmd.exe"; 
startInfo.Arguments = arguments; 
process.StartInfo = startInfo; 
process.Start(); 
+0

謝謝!有人可以更好地閱讀我的代碼,然後創作者Lol。 – Doggo123445