【问题标题】:ProcessStartInfo - print output in console window AND to file (C#)ProcessStartInfo - 在控制台窗口和文件中打印输出(C#)
【发布时间】:2012-05-10 11:21:55
【问题描述】:

从我的 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 可执行文件)?

【问题讨论】:

    标签: c# process console processstartinfo


    【解决方案1】:

    您需要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
    }
    

    【讨论】:

      【解决方案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);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-20
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多