我在 C# 中编写了一个简单的应用程序来开始使用,以重定向您在自己的应用程序中启动应用程序(在本例中为服务器)所需的 I/O 流。
首先我们创建一个System.Diagnostics.Process 类的新实例
var process = new Process();
然后我们指定开始信息
process.StartInfo = new ProcessStartInfo
{
FileName = Console.ReadLine(), //Reads executable path from console
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
然后我们添加一个事件处理程序,在这个例子中它只是写入带有“>”前缀的行
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");
现在我们可以通过调用Process#Start()来启动这个过程
process.Start();
最后我们可以调用Process#BeginOutputReadLine() 没有这个OutputDataReceived 事件将永远不会触发
process.BeginOutputReadLine();
要发送命令,您可以使用进程'StandardInput 流
process.StandardInput.WriteLine("command");
带有示例输出的完整工作代码(使用 cmd.exe 测试,但必须与 MC 服务器一起使用)
代码:
static void Main(string[] args)
{
Console.Write("Enter executable path: ");
var process = new Process();
process.StartInfo = new ProcessStartInfo
{
FileName = Console.ReadLine(), //Reads executable path, for example cmd is the input
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine($"> {e.Data}");
process.Start();
process.BeginOutputReadLine();
process.StandardInput.WriteLine("echo a");
//Prevent closing
Console.ReadKey();
}
输出:
Enter executable path: cmd
> Microsoft Windows [Version 10.0.18362.239]
> (c) 2019 Microsoft Corporation. Minden jog fenntartva.
>
> F:\VisualStudio\StackOverflow\StackOverflow\bin\Debug\netcoreapp2.1>echo a
> a
>