允许和拒绝访问

本文关键字:拒绝访问 | 更新日期: 2023-09-27 18:18:49

我怎样才能告诉程序只有在我输入正确的密码时才给予访问权限?

谢谢。

namespace Password
{
  class Program
  {
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter password:");
        Console.ReadLine();

        string Password = "Test";
        bool PassWordMatch;
        PassWordMatch = Password == "Test";
        if (PassWordMatch)
        {
            Console.WriteLine(" Password Match. Access Granted");
        }
        else
        {
           Console.WriteLine("Password doesn't match! Access denied.");
        }
    }
}

}

允许和拒绝访问

您可以使用Console.ReadLine方法,它将返回用户输入的值,您可以将其存储在相应的变量中:

namespace Password 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Console.WriteLine("Please enter password:"); 
            string password = Console.ReadLine();
            bool passWordMatch;
            passWordMatch = password == "Test";
            if (passWordMatch)
            {
                Console.WriteLine(" Password Match. Access Granted");
            }
            else
            {
                Console.WriteLine("Password doesn't match! Access denied.");
            }
        }
    }
}

你就快成功了。

Console.ReadLine()方法读取标准输入流并返回string。您只需要传递此方法返回的新字符串并将其与测试密码进行比较。

Console.WriteLine("Please enter password:");
string input = Console.ReadLine();
bool PassWordMatch = input == "Test";
if(PassWordMatch)
   Console.WriteLine(" Password Match. Access Granted");
else
   Console.WriteLine("Password doesn't match! Access denied.");

当然,这不是一个很好的方法在您的应用程序的安全性

您没有将读字符串分配给变量,因此它进一步不可用于比较。

Console.ReadLine()函数可用于从输入流中读取下一行字符,如果没有更多行可用,则返回null

你可以这样做:

namespace Password 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Console.WriteLine("Please enter password:"); 
            string password = Console.ReadLine(); //Assign user-entered password 
            bool passWordMatch;
            passWordMatch = password == "Test";
            if (passWordMatch)
            {
                Console.WriteLine(" Password Match. Access Granted");
            }
            else
            {
                Console.WriteLine("Password doesn't match! Access denied.");
            }
        }
    }
}