首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 控制台讀取密碼:隱藏輸入與退格鍵支援

     編輯:關於C#

效果展示

輸入密碼時顯示 *,支援 Backspace 刪除,Enter 確認,完全模擬 Linux 終端體驗。

核心實作


public static string ReadPassword()
{
    var sb = new StringBuilder();
    // 用於處理退格鍵的視覺效果:\b \b (左移、覆蓋空格、再左移)
    var backspaceSequence = new char[] { '\b', ' ', '\b' };

    while (true)
    {
        var key = Console.ReadKey(intercept: true); // 不顯示原始字元
        
        if (key.Key == ConsoleKey.Enter)
        {
            Console.WriteLine(); // 換行
            break;
        }
        
        if (key.Key == ConsoleKey.Backspace)
        {
            if (sb.Length > 0)
            {
                sb.Length--; // 移除最後一字元
                Console.Write(backspaceSequence); // 視覺上刪除一個 *
            }
            continue;
        }
        
        // 一般可列印字元
        if (!char.IsControl(key.KeyChar))
        {
            sb.Append(key.KeyChar);
            Console.Write('*');
        }
        // 忽略其他控制字元 (Ctrl+C 等)
    }
    
    return sb.ToString();
}

使用範例


static void Main()
{
    Console.Write("使用者名稱: ");
    var username = Console.ReadLine();
    
    Console.Write("密碼: ");
    var password = ReadPassword();
    
    Console.WriteLine($"\n登入中... User={username}, Pass.Length={password.Length}");
    // 驗證邏輯...
}

進階增強版


public static string ReadPassword(string prompt = "密碼: ", char maskChar = '*', bool showLength = false)
{
    Console.Write(prompt);
    var sb = new StringBuilder();
    var backspace = new char[] { '\b', ' ', '\b' };

    while (true)
    {
        var key = Console.ReadKey(true);
        
        if (key.Key == ConsoleKey.Enter) break;
        
        if (key.Key == ConsoleKey.Backspace)
        {
            if (sb.Length > 0)
            {
                sb.Length--;
                Console.Write(backspace);
                if (showLength) Console.Write("\b \b"); // 同步更新長度顯示
            }
            continue;
        }
        
        if (key.Key == ConsoleKey.Escape)
        {
            // ESC 取消輸入
            Console.WriteLine("\n已取消");
            return null;
        }
        
        if (!char.IsControl(key.KeyChar))
        {
            sb.Append(key.KeyChar);
            Console.Write(maskChar);
            if (showLength) Console.Write($" ({sb.Length})");
        }
    }
    
    Console.WriteLine();
    return sb.ToString();
}

注意事項

項目說明
Console.ReadKey(true)intercept=true 關鍵:攔截按鍵不自動顯示
退格處理\b \b 序列實現視覺刪除,跨平台相容
控制字元過濾char.IsControl 過濾 Ctrl+鍵、功能鍵等
安全性回傳明文密碼,使用後應立即 Array.Clear 或用 SecureString (較複雜)
重導向輸入管道/檔案重導向時 Console.ReadKey 可能拋出例外,需 try-catch 降級用 Console.ReadLine

SecureString 版本 (更安全)


using System.Security;

public static SecureString ReadSecurePassword()
{
    var pwd = new SecureString();
    var backspace = new char[] { '\b', ' ', '\b' };

    while (true)
    {
        var key = Console.ReadKey(true);
        if (key.Key == ConsoleKey.Enter) break;
        if (key.Key == ConsoleKey.Backspace)
        {
            if (pwd.Length > 0)
            {
                pwd.RemoveAt(pwd.Length - 1);
                Console.Write(backspace);
            }
            continue;
        }
        if (!char.IsControl(key.KeyChar))
        {
            pwd.AppendChar(key.KeyChar);
            Console.Write('*');
        }
    }
    Console.WriteLine();
    pwd.MakeReadOnly();
    return pwd;
}

// 使用時轉為字串 (僅在必要時)
string plain = new System.Net.NetworkCredential("", securePwd).Password;

簡單實用的 ReadPassword 方法,能大幅提升控制台應用程式的專業度與安全性體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved