I'm trying to run an external binary from a C# code using the ProcessEx.RunAsync command. However, this binary doesn't have a quiet mode and whenever it's done operating, it prompts "press enter to continue" in order to exit the program. How do I handle this so I won't get a timeout return?
Asked
Active
Viewed 294 times
-2
-
1Redirect stdin, then write a "\n" into it? – Jeremy Lakeman Aug 24 '21 at 01:12
-
@JeremyLakeman Can you give more details? I'm quite unfamiliar with this approach. Thanks. – MK Span Aug 24 '21 at 01:19
-
Pick a duplicate question; https://stackoverflow.com/search?q=%5Bc%23%5D+redirect+standard+input – Jeremy Lakeman Aug 24 '21 at 01:26
1 Answers
0
The functionality you describe is similar to what expect tool provides in *nix world.
The program automates interactions with programs that expose a text terminal interface.
There are various options available for you to use and if you are interested in using an existing C# library then the dotnetexpect might solve it for you; note it is quite old.
If you are looking for all hand-coding, here is a PoC to explain the concept. As usual: don't use as-is this is just to demonstrate the concept.
namespace ToExpectOrNotToExpect
{
class Program
{
static void RunAndManage(string command,string args)
{
Process processHandle = new Process();
processHandle.StartInfo.FileName = command;
processHandle.StartInfo.Arguments = args;
processHandle.StartInfo.UseShellExecute = false;
processHandle.StartInfo.RedirectStandardOutput = true;
processHandle.StartInfo.RedirectStandardInput = true;
processHandle.StartInfo.CreateNoWindow = false;
processHandle.Start();
string data = "";
while (!processHandle.StandardOutput.EndOfStream)
{
// Cheap and cheeky buffer: improve
char[] buffer = new char[256];
int n = processHandle.StandardOutput.Read(buffer, 0, 100);
data += new string(buffer, 0, n);
Console.WriteLine("GOT: [[ " + data + "]]");
if (data.IndexOf("Press any key") >= 0)
{
processHandle.StandardInput.Write('\r');
// Keeping it simple and exiting for the PoC: improve this in your implementation
break;
}
}
}
static void Main(string[] args)
{
RunAndManage("cmd.exe", " /c echo This was fun && echo Really && echo Really && pause && echo Wowzer Pause Bypassed 1>&2 ");
}
}
}
Output would look something like this (notice that we sent CarriageReturn once we saw the pause text being emitted):
Detailed and expansive examples are plenty on this idea on Stackoverflow and elsewhere. Here is one.

chkdsk
- 1,187
- 6
- 20