2

在我的 C# 应用程序中,我使用以下 ProcessStartInfo 调用 Process.Start(myPSI):

ProcessStartInfo startInfoSigner = new ProcessStartInfo();
startInfoSigner.CreateNoWindow = false;
startInfoSigner.UseShellExecute = false;
startInfoSigner.FileName = pathToMyEXE;
startInfoSigner.WindowStyle = ProcessWindowStyle.Hidden;
startInfoSigner.WindowStyle = ProcessWindowStyle.Minimized;

startInfoSigner.RedirectStandardOutput = true;

这会在运行应用程序时打开一个新的控制台窗口,并且不会产生任何输出(因为它已被重定向)。我读取 exe 进程标准输出并将其写入文件。

有没有办法在这个新的控制台窗口中仍然显示信息,并将其写入文件(不修改 pathToMyEXE 可执行文件)?

4

2 回答 2

2

此代码应该为您提供有关如何完成任务的基本概念:

class Tee
{
    private readonly string m_programPath;
    private readonly string m_logPath;
    private TextWriter m_writer;

    public Tee(string programPath, string logPath)
    {
        m_programPath = programPath;
        m_logPath = logPath;
    }

    public void Run()
    {
        using (m_writer = new StreamWriter(m_logPath))
        {

            var process =
                new Process
                {
                    StartInfo =
                        new ProcessStartInfo(m_programPath)
                        { RedirectStandardOutput = true, UseShellExecute = false }
                };

            process.OutputDataReceived += OutputDataReceived;

            process.Start();
            process.BeginOutputReadLine();
            process.WaitForExit();
        }
    }

    private void OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine(e.Data);
        m_writer.WriteLine(e.Data);
    }
}
于 2012-04-30T19:10:28.793 回答
2

您需要RedirectStandardOutput = true为了处理OutputDataReceived事件。在事件处理程序中执行日志记录并将数据写回控制台。

private void OutputDataReceived(object sender, DataReceivedEventArgs e) 
{ 
         logger.log(someString);//write to the file
         Console.WriteLine(e.Data);//still display the info in this new console window
}
于 2012-04-30T19:22:30.600 回答