How to hide the text entered in a .NET console application

You’ve probably encountered console applications that ask for a password. It’s very likely that the password will stay hidden otherwise other people viewing your screen can easily read it.

This short post will present a possible solution on how to achieve a hidden string input in a .NET console application.

The key feature to bear in mind is the overloaded Console.ReadKey method where you can pass in a boolean parameter. A ‘true’ means that the given character typed should be intercepted, i.e. not shown in the console window. We continue reading the characters until it is equal to the new line character ‘\r’ which closes the while loop. We store the password characters in a string builder. Unfortunately the ReadLine method has no equivalent overload which would turn the solution into a one-liner.

Here it comes in code:

Console.Write("You password please: ");
StringBuilder passwordBuilder = new StringBuilder();
bool continueReading = true;
char newLineChar = '\r';
while (continueReading)
{
	ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(true);
	char passwordChar = consoleKeyInfo.KeyChar;

	if (passwordChar == newLineChar)
	{
		continueReading = false;
	}
	else
	{
		passwordBuilder.Append(passwordChar.ToString());
	}
}
Console.WriteLine();
Console.Write("Your password in plain text is {0}", passwordBuilder.ToString());

You can even hide the blinking cursor with the following code:

Console.Write("You password please: ");
Console.CursorVisible = false;

Just don’t forget to set the visibility back to true later on.

View all various C# language feature related posts here.

Advertisement

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

3 Responses to How to hide the text entered in a .NET console application

  1. lenandlar says:

    Thanks. Do you have an intro to .net tutorial I could look at

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 )

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

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

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

%d bloggers like this: