读取运行Process的输出为null

时间:2017-09-06 13:40:35

标签: c# .net-4.0

我试图运行编译应用程序的过程(旧的基本编译器)。我故意在应用程序中出错我试图编译以查看我如何读取可能返回的任何输出消息,但我只在e.Data中看到null。有人可以告诉我下面的代码是否有什么问题试图读取输出或错误数据吗?

private static void RunProcess(string filename, string args)
{
    try
    {
        var processStartInfo = new ProcessStartInfo();

        processStartInfo.FileName = filename;

        processStartInfo.Arguments = args;

        processStartInfo.UseShellExecute = false;

        processStartInfo.RedirectStandardOutput = true;

        processStartInfo.RedirectStandardError = true;

        var result = string.Empty;

        using (Process process = Process.Start(processStartInfo))
        {
            process.ErrorDataReceived += Process_ErrorDataReceived;

            process.OutputDataReceived += Process_OutputDataReceived;

            process.BeginOutputReadLine();

            process.BeginErrorReadLine();

            process.WaitForExit();

            Console.Write("Completed process with an exit code of: " + process.ExitCode.ToString() + Environment.NewLine);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

private static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data);
}

private static void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine(e.Data);
}

0 个答案:

没有答案