从控制台应用程序到另一个c#控制台应用程序的输入

本文关键字:控制台 应用程序 输入 另一个 | 更新日期: 2023-09-27 18:29:16

我想开发一个输入到另一个c#应用程序(b.exe)的c#应用程序(a.exe)b.exe不接受任何参数。

b.exe -call or b.exe call等不工作

当我从cmd打开b.exe时,它会接受这样的参数:

b:call
b:command 2
....
b:command n

如何从a.exe馈送b.exe

我用过,但不起作用。

        var psi = new ProcessStartInfo("b.exe")
        {
            RedirectStandardInput = true,
            RedirectStandardOutput = false,
            UseShellExecute = false
        };
        var p = new Process { StartInfo = psi };
        p.Start();
        p.StandardInput.WriteLine("call");

从控制台应用程序到另一个c#控制台应用程序的输入

以下是我从您的问题中了解到的内容:

  • a.exe启动b.exe
  • a.exe使用命令行参数或标准输入将命令/请求传递给b.exe
  • b.exe接收命令/请求并通过StandardOutput传递信息

使用命令行参数稍微简单一些,只是您需要为每个请求/命令多次运行b.exe

// b.exe
static void Main(string[] args)
{
    // using command line arguments
    foreach (var arg in args)
        ProcessArg(arg);
    // if using input, then use something like if processing line by line
    // string line = Console.ReadLine();
    // while (line != "exit" || !string.IsNullOrEmpty(line))
    //     ProcessArg(line);
    // or you can read the input stream
    var reader = new StreamReader(Console.OpenStandardInput());
    var text = reader.ReadToEnd();
    // TODO: parse the text and find the commands
}
static void ProcessArg(string arg)
{
    if (arg == "help") Console.WriteLine("b.exe help output");
    if (arg == "call") Console.WriteLine("b.exe call output");
    if (arg == "command") Console.WriteLine("b.exe command output");
}
// a.exe
static void Main(string[] args)
{
    // Testing -- Send help, call, command  --> to b.exe
    var psi = new ProcessStartInfo("b.exe", "help call command")
    {
        RedirectStandardError = true,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        UseShellExecute = false,
    };
    var p = new Process() { StartInfo = psi };
    p.ErrorDataReceived += p_ErrorDataReceived;
    p.OutputDataReceived += p_OutputDataReceived;
    p.Start();
    p.BeginErrorReadLine();
    p.BeginOutputReadLine();
    // if sending data through standard input (May need to use Write instead
    // of WriteLine. May also need to send end of stream (0x04 or ^D / Ctrl-D)
    StreamWriter writer = p.StandardInput;
    writer.WriteLine("help");
    writer.WriteLine("call");
    writer.WriteLine("exit");
    writer.Close();
    p.WaitForExit();
}
static void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.Error.WriteLine("a.exe error: " + e.Data ?? "(null)");
}
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Console.WriteLine("a.exe received: " + e.Data ?? "(null)");
}

查看OutputDataReceived和ErrorDataReceived事件以及这些方法中的MSDN示例。

一个需要考虑的问题是,不能通过管道从具有管理权限的程序中输出。您需要保存输出,然后将输出传递给其他程序。

不久前,我发现了一个有用的带有ProcessRunner类的CSharpTest库。浏览ProcessRunner的"InternalStart"方法以获取示例。