用户名和密码输入代码验证

时间:2014-06-17 12:10:05

标签: c#

我使用login方法创建用户帐户。当按下回车键而不输入用户名和密码字段中的任何字符时,它将被存储在带有分隔符(:)的文件中,并且当尝试登录帐户而不输入任何字符时,帐户将被打开。我应该使用哪个验证码,在输入用户名和密码之前不会进入下一步?

public string getPassword()
{
    ConsoleKeyInfo key;
    string pass = "";
    do
    {
        key = Console.ReadKey(true);
        if (key.Key != ConsoleKey.Backspace)
        {
            pass += key.KeyChar;
            Console.Write("*");
        }
        else
        {
            try
            {
                pass = pass.Remove(pass.Length - 1);
                Console.Write("\b \b");
            }
            catch(Exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Password cannot be less than 0");
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("Re-enter password: ");
                Console.ForegroundColor = ConsoleColor.Yellow;
            }
        }
    } while (key.Key != ConsoleKey.Enter);
    return pass.Remove(pass.Length - 1);
}

public void Login()
{            
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.Write("\nEnter username: ");
    Console.ForegroundColor = ConsoleColor.Yellow;
    username = Console.ReadLine();
    Console.ForegroundColor = ConsoleColor.Cyan;
    Console.Write("Enter password: ");
    Console.ForegroundColor = ConsoleColor.Yellow;
    password = getPassword();
    Console.WriteLine("\n");
}

2 个答案:

答案 0 :(得分:1)

你可以尝试下面的代码,我想这就是你想要的

 Console.ForegroundColor = ConsoleColor.Cyan;
        Console.Write("\nEnter username: ");
        Console.ForegroundColor = ConsoleColor.Yellow;
        var username = Console.ReadLine();
        if (username != null && username.Length > 0)
        {
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.Write("Enter password: ");
            Console.ForegroundColor = ConsoleColor.Yellow;
            var password = getPassword();
            Console.WriteLine("\n");
        }
        else
        {
            Main();
        }

答案 1 :(得分:1)

你可以在if语句中使用字符串方法“isNullOrEmpty”。

if (!username.isNullOrEmpty)
   if (!password.isNullOrEmpty)
      // Do something

这将检查用户名和密码是否都填充了实际字符,而不是空格或空格或制表符等等。

相关问题