22 Jun 2011

在Console下输入密码,以星号代替。

Share

如何在Console下输入密码,像*unix系统下那样不显示,或者显示星号,如下代码经过测试:

/// <summary>
/// Gets the console secure password.
/// </summary>
/// <returns></returns>
private static SecureString GetConsoleSecurePassword( )
{
    SecureString pwd = new SecureString( );
    while ( true )
    {
        ConsoleKeyInfo i = Console.ReadKey( true );
        if ( i.Key == ConsoleKey.Enter )
        {
            break;
        }
        else if ( i.Key == ConsoleKey.Backspace )
        {
            pwd.RemoveAt( pwd.Length - 1 );
            Console.Write( "\b \b" );
        }
        else
        {
            pwd.AppendChar( i.KeyChar );
            Console.Write( "*" );
        }
    }
    return pwd;
}

/// <summary>
/// Gets the console password.
/// </summary>
/// <returns></returns>
private static string GetConsolePassword( )
{
    StringBuilder sb = new StringBuilder( );
    while ( true )
    {
        ConsoleKeyInfo cki = Console.ReadKey( true );
        if ( cki.Key == ConsoleKey.Enter )
        {
            Console.WriteLine( );
            break;
        }

        if ( cki.Key == ConsoleKey.Backspace )
        {
            if ( sb.Length > 0 )
            {
                Console.Write( "\b\0\b" );
                sb.Length--;
            }

            continue;
        }

        Console.Write( '*' );
        sb.Append( cki.KeyChar );
    }

    return sb.ToString( );
}

gist:https://gist.github.com/1039424

comments powered by Disqus