2017-10-08 117 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