首页 > 代码库 > 从控制台中读取密码 - C#

从控制台中读取密码 - C#


Tip :    从控制台中读取密码

语言: C#

______________________________________________________________

在登陆Linux系统的时候,体验过在Linux的shell命令行窗口中输入用户密码吗? 下面体验下在Windows控制台中输入密码的方式


Showing  Effect



SourceCode

        /// <summary>
        /// Read password from console
        /// </summary>
        /// <returns>password</returns>
        public static string ReadPassword()
        {
            char[] revisekeys = new char[3];
            revisekeys[0] = (char)0x08;
            revisekeys[1] = (char)0x20;
            revisekeys[2] = (char)0x08;

            StringBuilder sb = new StringBuilder();
            while (true)
            {
                ConsoleKeyInfo kinfo = Console.ReadKey(true);

                if (kinfo.Key == ConsoleKey.Enter)
                {
                    break;
                }

                if (kinfo.Key == ConsoleKey.Backspace)
                {
                    if (sb.Length != 0)
                    {
                        int rIndex = sb.Length-1;
                        sb.Remove(rIndex, 1);
                        Console.Write(revisekeys);
                    }
                    continue;
                }
                sb.Append(Convert.ToString(kinfo.KeyChar));
                Console.Write("*");
            }
            return sb.ToString();
        }