Search code examples
c#consolewindows-10console-application

IO On Another Console Application


I have two console applications written in C#, and running on Windows 10. I want the first console application to be able to enter keys into the second console application, and be able to get the second console's output.

Here is a hypothetical example: Say the second console, on receiving a predetermined password, would respond with "true", but "false" otherwise. My first console would then want to know whether a certain string of text was the password. How would it enter the text into the second console, and receive the second console's output?

This seems like the sort of very general question that would have been asked hundreds of times before. However, in my searches, I was not able to find a single solution. Any help would be greatly appreciated!


Solution

  • I found the following solution:

    Console 1:

    using System.Diagnostics;
    using static System.Console;
    const string path = @"C:\path\Console2.exe";
    using Process process = new();
    process.StartInfo.FileName = path;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.Start();
    StreamWriter input = process.StandardInput;
    StreamReader output = process.StandardOutput;
    input.WriteLine("ping");
    string? output = output.ReadLine();
    WriteLine(output);
    ReadKey(true);
    output.ReadToEnd();
    process.WaitForExit();
    return;
    

    Console 2:

    using static System.Console;
    string? input = ReadLine();
    if (input == "ping")
        WriteLine("true");
    else
        WriteLine("false");