Thursday 17 September 2015

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:


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



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

0 comments:

Post a Comment