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:

London
Stockholm
Budapest
München
Birmingham

…, 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);
	Console.SetIn(sourceFileReader);

	string city = null;
	do
	{
		city = Console.ReadLine();
		Console.WriteLine(city);
	}
	while (city != null);
}

View all various C# language feature related posts here.

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

iReadable { }

.NET Tips & Tricks

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: