How to redirect standard input for a .NET console application

Normally .NET console applications read their input from the console through Console.ReadLine(). The user is prompted for some input, they enter some text, press enter and the console can read this input.

However, this is not the only option you have. The standard input channel can be overridden.

All you need is an object which derives from the abstract TextReader class. There are a couple of classes in .NET that derive from this base class, such as StringReader and StreamReader.

If you’re interested in how to implement your own TextReader class you can start from this MSDN blog post.

We’ll look at an example using StreamReader, i.e. we’ll tell the console to “read the lines” from a file instead of waiting for the user to write something in the console and press enter. The Console.SetIn method is the most important method to remember if you want to redirect the standard input.

Suppose you have a file called cities.txt with the following content:


…, i.e. one city per line then the following code will read all of them and show them in the console:

static void Main(string[] args)
	FileInfo sourceFile = new FileInfo(@"c:\cities.txt");
	TextReader sourceFileReader = new StreamReader(sourceFile.FullName);

	string city = null;
		city = Console.ReadLine();
	while (city != null);

View all various C# language feature related posts here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: