Frage

From my C# application, I am calling Process.Start(myPSI) with the following ProcessStartInfo:

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

startInfoSigner.RedirectStandardOutput = true;

This brings up a new console window when running the application, and produces no output (since it is redirected). I read the exe process standard output and write it to a file.

Is there a way to still display the info in this new console window, AND write it to a file (without modifying the pathToMyEXE executable file)?

War es hilfreich?

Lösung

You need RedirectStandardOutput = true in order to handle the OutputDataReceived Event. In the event handler perform the logging and write the data back to the console.

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
}

Andere Tipps

this code should give you the basic idea of how to accomplish your task:

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);
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top