How to hide the text entered in a .NET console application
September 2, 2015 3 Comments
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.
Thanks. Do you have an intro to .net tutorial I could look at
Thanks for your comment, no, I have no tutorial dedicated to .NET/C# but there must thousands available online. //Andras
How would I go about using backspace to delete characters in this code?