How to hide content in the console using C#?
In C#, you can use the Console.ReadKey method to hide the user’s input. The specific code is shown below:
using System;
class Program
{
static void Main()
{
Console.Write("请输入密码:");
string password = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
password += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && password.Length > 0)
{
password = password.Substring(0, (password.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
Console.WriteLine("您输入的密码是:" + password);
}
}
When users enter their password in the code above, the console will display asterisks (*) instead of the actual characters entered by the user to hide the password content.