无法读取从代码运行的控制台命令的输出

无法读取从代码运行的控制台命令的输出

问题描述:

我正在构建一个小型控制台应用程序,有时会使用Windows命令行来发送命令,然后接收并显示输出。无法读取从代码运行的控制台命令的输出

打开一个新的命令行实例很容易,从我的应用程序发送命令需要一点挖掘,但它的工作。不过,我似乎无法读取命令行的输出。

我的代码是基于:

How to redirect Standard Input/Output of an application

How do I run Command line commands from code

我申请的读取输出到我的应用程序相同的方式,而这是行不通的,直到那一刻我关闭我的应用程序,而正在关机时,我可以看到输出。

它的工作,但很可能我有错位的代码,这阻止我看到输出,直到我开始关闭我的应用程序。

有人可以帮助我吗?

代码:

 Process p = new Process(); 
     p.StartInfo.FileName = Environment.GetEnvironmentVariable("comspec"); 
     p.StartInfo.ErrorDialog = false; 
     p.StartInfo.UseShellExecute = false; 
     p.StartInfo.RedirectStandardError = true; 
     p.StartInfo.RedirectStandardInput = true; 
     p.StartInfo.RedirectStandardOutput = true; 

     //Execute the process 
     if (p.Start()) 
     { 
      //Get the output stream 
      StreamReader outputReader = p.StandardOutput; 
      StreamReader errorReader = p.StandardError; 

      // Assign a Stream Writer to send the Commands 
      StreamWriter commandWriter = p.StandardInput; 

      // Send the "Dir" command to the command line instance. 
      commandWriter.Write("dir"); 
      commandWriter.Write(commandWriter.NewLine); 

      p.WaitForExit(); 

      //Display the result 
      Console.WriteLine(outputReader.ReadToEnd()); 

      outputReader.Close(); 
      errorReader.Close(); 
      commandWriter.Close(); 
     } 

的问题是,你不告诉的cmd.exe退出。完成后只需发送“exit \ r \ n”。

您最终会遇到的另一个问题是您需要异步读取stdout和stdin。

​​
+0

当然,我完全忘了它。感谢您的提升。 – 2011-01-14 17:17:47