Friday, February 11, 2022

Code Snippet - Read Password from Console C#

 Code Snippet - Read Password from Console C#

        The following code snippet shows how to read string from console without outputting the typed in characters, useful for reading passwords etc...

        The important difference is to use Console.ReadKey(true) for reading each character instead of Console.ReadKey() or Console.ReadLine().


var sb = new StringBuilder();

    while (true)

    {

        var c = Console.ReadKey(true);

        if (c.Key == ConsoleKey.Enter)

            break;

        sb.Append(c.KeyChar);

    }


    return sb.ToString();


Code Snippet - Read Password from Console C#

No comments:

Post a Comment

25% off sale & plans of Trustworthy and Responsible AI

25% off sale until 12/04/2024! This sale is for ThanksGiving, BlackFriday and CyberMonday sale. A minor update was done. This update had...