我有一个exe(C#应用程序,同时具有gui和控制台输出(用于某些日志记录)),该文件会启动批处理文件。有时我从另一个批处理文件启动此exe。有问题的情况是这样的:
- I open a console (let's call it the initial console);
- I start the batch file 1 from that console;
- batch1 launches the exe;
- exe launches batch file 2.
问题在于,尽管在初始控制台中写入了自己的日志记录输出,但exe为batch2启动了新控制台。我还希望在初始控制台中输出batch2。我该怎么办?
答案 0 :(得分:0)
请确保您可以编辑“ exe”程序,您需要做的是“隐藏”第二个控制台(批处理)并将其输出重定向到字符串中,您需要执行以下操作:
string myoutput = string.empty;
Process process = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo("cmd.exe", @"/C c:\test.bat");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
process.StartInfo = startinfo;
process.OutputDataReceived += (s, args) => myoutput += args.Data;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
//Use myoutput as you like :)
编辑:我无法重现您的问题...也许您可以尝试以下其他方式:
Process process = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo("cmd.exe", @"/C c:\test.bat");
startinfo.RedirectStandardOutput = true;
startinfo.RedirectStandardError = true;
startinfo.UseShellExecute = false;
process.StartInfo = startinfo;
//process.OutputDataReceived += (s, args) => myoutput += args.Data;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string output_ERR = process.StandardOutput.ReadToEnd();