是否有办法将控制台应用程序的输入/输出连接到另一个程序的输出/输入 [英] Is there a way to conect the input/output of a console application to the output/input of another program

查看:35
本文介绍了是否有办法将控制台应用程序的输入/输出连接到另一个程序的输出/输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无法编辑的应用程序,该应用程序从控制台读取并向其写入,我想知道如何读取该程序所说的内容并将命令写回该程序。

这是为"我的世界"服务器准备的,在那里我想要读取玩家所说的内容,并根据所说的内容运行命令。(服务器是我无法编辑的应用程序)

我无法为服务器创建修改,因为我使用的mod检查是否对文件进行了任何其他修改,如果是,则无法加载。

推荐答案

首先,我用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:VisualStudioStackOverflowStackOverflowinDebug
etcoreapp2.1>echo a
> a
>

这篇关于是否有办法将控制台应用程序的输入/输出连接到另一个程序的输出/输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆