C# :: Aufgabe #138 :: Lösung #6
6 Lösungen

#138
Console - ReadPassword Methode
Anfänger - C#
von DrizZle
- 15.06.2016 um 13:48 Uhr
Ihr kennt sicherlich die Einstellung für die TextBox in der Windows Form in der man den User Input sofort in ein belibigen Password Char umwandeln kann (in der Regel '*'). Diese Möglichkeit hat man in der Console nicht. Die Aufgabe besteht darin jeden Tastaturschlag des Users abzufangen und in ein '*' umzuwandeln und auszugeben. Sprich ihr erstellt eure eigene Read Methode. Das Passwort soll später trotz allem als Text ausgegeben werden können.
Vorlage:
C#-Code
Vorlage:

class ReadPass { static void main(string[] args) { Console.Write("Passwort: "); string password = ReadPassword(); } string ReadPassword() { ... } }
#6

von Exception (7090 Punkte)
- 05.05.2018 um 13:13 Uhr

using System; namespace ReadPassword { class Program { static void Main(string[] args) { printLogo(); Console.Write("> "); string password = readPassword(); Console.Clear(); printLogo(); Console.WriteLine("> " + password); Console.ReadKey(); } /// <summary> /// Ersetzt jede Eingabe durch ein Asterisks. /// Steuerzeichen werden ignoriert. /// Backspace und Enter bilden hierbei eine Ausnahme. /// Backspace: Löscht letztes Zeichen aus String, löscht letztes Asterisks. /// Enter: Wenn Enter gedrückt wird, so wird die Schleife verlassen, die Methode gibt das Passwort zurück. /// </summary> /// <returns>Passwort im Klartext</returns> static string readPassword() { bool enterPressed = false; string pwd = ""; do { ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); // schnappe infos pwd += (consoleKeyInfo.KeyChar >= 32 && consoleKeyInfo.KeyChar <= 126) ? consoleKeyInfo.KeyChar.ToString() : ""; // füge jedes Zeichen hinzu welches im Wertebereich zwischen 32 und 126 liegt ("Space" - "~") // somit werden steuerzeichen ignoriert. Console.Write("\b"); // lösche letztes zeichen Console.Write("*"); // setze asterisks an diese stelle if (consoleKeyInfo.Key == ConsoleKey.Backspace) // Backspace gedrückt? Ja: Lösche letztes Zeichen { pwd = pwd.Substring(0, pwd.Length - 1); Console.Clear(); printLogo(); Console.Write("> "); foreach (char c in pwd) { Console.Write("*"); } } else if((consoleKeyInfo.KeyChar < 32 || consoleKeyInfo.KeyChar > 126) && consoleKeyInfo.Key != ConsoleKey.Enter) // lösche asterisks von zeichen wie zb escape { Console.Clear(); printLogo(); Console.Write("> "); foreach (char c in pwd) { Console.Write("*"); } } else if(consoleKeyInfo.Key == ConsoleKey.Enter) // Enter gedrückt? Ja: Ende! { enterPressed = true; } } while (!enterPressed); return pwd; } /// <summary> /// Gibt ein Logo aus. /// #Style :) /// </summary> static void printLogo() { Console.BackgroundColor = ConsoleColor.DarkRed; Console.WriteLine(" "); Console.WriteLine(" Passworteingabe "); Console.WriteLine(" "); Console.BackgroundColor = ConsoleColor.Black; } } }
Kommentare:
Für diese Lösung gibt es noch keinen Kommentar
Seite 1 von 0
1