在我的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可执行文件)?
答案 0 :(得分: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
}
答案 1 :(得分:1)
此代码应该为您提供如何完成任务的基本知识:
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);
}
}