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:
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.