如何重定向控制台的输出
本文关键字:输出 控制台 重定向 | 更新日期: 2023-09-27 18:21:13
我目前正在尝试从外部控制台应用程序读取输出流。我无法修改此应用程序。
这是我目前使用的代码:
Process process = new Process();
string dir = Directory.GetCurrentDirectory();
process.StartInfo.FileName = dir + "/volibot.exe";
process.StartInfo.UseShellExecute = false;
process.Start();
//do some stuff with the stream
我用它来读取输出流:
while (!process.StandardOutput.EndOfStream)
{
string message = process.StandardOutput.ReadLine();
Console.WriteLine(message);
}
但每当我加上:
process.StartInfo.RedirectStandardOutput = true;
我得到这个错误:
Unhandled exception: System.IO.IOException: The handle is invalid.
bij System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
bij System.IO.__Error.WinIOError()
bij System.Console.SetWindowSize(Int32 width, Int32 height)
bij RitoBot.Core.Main(String[] args)
这没有意义,因为这是一个控制台应用程序?如何解决此问题?或者周围有简单的工作吗?
编辑:尝试过:ProcessInfo和RedirectStandardOutput
static void Main(string[] args)
{
//C:''Users''pc''Documents''Visual Studio 2013''Projects''ConsoleApplication1''ConsoleApplication1''bin''Debug''VoliBot.exe
Process build = new Process();
build.StartInfo.WorkingDirectory = @"C:''Users''pc''Documents''Visual Studio 2013''Projects''ConsoleApplication1''ConsoleApplication1''bin''Debug''";
build.StartInfo.Arguments = "";
build.StartInfo.FileName = "volibot.exe";
build.StartInfo.UseShellExecute = false;
build.StartInfo.RedirectStandardOutput = true;
build.StartInfo.RedirectStandardError = true;
build.StartInfo.CreateNoWindow = true;
build.ErrorDataReceived += build_ErrorDataReceived;
build.OutputDataReceived += build_ErrorDataReceived;
build.EnableRaisingEvents = true;
build.Start();
build.BeginOutputReadLine();
build.BeginErrorReadLine();
build.WaitForExit();
Console.ReadLine();
}
static void build_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
string strMessage = e.Data;
Console.WriteLine(strMessage);
}
仍然不起作用:s
尝试以下操作:
var psi = new ProcessStartInfo(@"c:'temp'mycommand.exe", String.Format(" '"{0}'" '"{1}'" '"{2}'"", sourceDoc, dataSource, outputFile))
{
WorkingDirectory = Environment.CurrentDirectory,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = false
};
using (var process = new Process { StartInfo = psi })
{
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
// wait for the process to exit
process.WaitForExit();
if (process.ExitCode != 0)
{
}
}
}
您有@"C:''Users''pc''Documents…."当你使用@符号时,你不需要双重''。.
也许就是这样?