Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a Console application to talk to itself by simulating user input – Console.WriteLine() and Console.Readline()?

I have a console application built (like a terminal) where user is asked for their input.

Now I want to extend this application by completely automating it. Instead of the user having to type "1", "2", "3" – the console application would end up simulating the user input instead:

  • types "1"
  • waits 1 second
  • types "2"
  • waits 1 second
  • types "3"

Here is some oversimplified code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

string userInput = Console.ReadLine();
Console.WriteLine("hello");
Console.WriteLine("user wrote to me: " + userInput); // This should output "user wrote to me: hello"

The problem is that basically the thread stops on Console.Readline() and waits for input. How can I avoid that?

Creating a separate thread to run Console.ReadLine() did not work.

I am aware that this is not the best approach to the problem, but I would like to make as little changes as possible (I do not want to refactor the code).

>Solution :

Something like:

using System;
using System.IO;

Console.SetIn(new StringReader(@"hello
more lines
here"));

string userInput;
while ((userInput = Console.ReadLine()) is not null)
{
    Console.WriteLine("user wrote to me: " + userInput);
}

Obviously you can use your own custom TextReader for more advanced scenarios (for example to insert time delays via Thread.Sleep or Task.Delay, or to invent values rather than having to hard-code them), and similarly you can use SetOut with your own TextWriter to intercept output.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading