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

OutputDataReceivedイベントRedirectStandardOutput = trueを処理するために必要です。イベントハンドラーでロギングを実行し、データをコンソールに書き戻します。

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 に答える