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

时间:2011-01-14 16:53:26

标签: c#

我正在构建一个小型控制台应用程序,有时会使用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();
        }

1 个答案:

答案 0 :(得分:4)

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

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

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        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;
        // Hook up async stdout and stderr reading
        p.ErrorDataReceived += ConsoleDataReceived;
        p.OutputDataReceived += ConsoleDataReceived;

        // Execute the process
        if (p.Start())
        {
            // Begin async stdout and stderr reading
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            // Send the "Dir" command to the command line instance.
            p.StandardInput.WriteLine("dir");

            // Send "exit" and wait for exit
            p.StandardInput.WriteLine("exit");
            p.WaitForExit();
        } 
    }

    static void ConsoleDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (e.Data != null)
            Console.WriteLine(e.Data);
    }
}
相关问题