如何将用户凭据与 C# 中的文本文件内容进行匹配

How to match user credentials against text file contents in C#

我正在尝试创建一个登录方法,该方法根据名为 "accounts.txt" 的文本文件检查用户凭据,该文件包含 "Bob password" 已经登录了。

login 方法参数如 - "login" 是 command,用户名(例如 "Bob")是 param1 和密码(例如 "password*44") 是 param2.

当我 运行 命令行参数时,一个例子是 "login Bob password" 并且该方法应该逐行读取文件的内容,直到找到匹配项和 returns "login Bob successful"。否则它会说 "invaild username/password".

我不确定该怎么做,欢迎提供任何提示。这是我当前的代码

protected void login(string command, string param1, string param2) // string command "login" string username, string password
{
     // login command
     // Needs to check accounts.txt file for username and password.
     // if username and password exists, provide logon message
     // if username and/ or password does not exist, provide failed logon message.
     // IN MEMORY store current login username and password

     //checks accounts.txt file if username already exists and if there is a match

     if (not sure what arg would go here)
     {
         string path = "C:\Files\accounts.txt";
         Console.WriteLine("username and password match", path);
     }
     else
     {
         Console.WriteLine("Login Failed: invaild username or password");
         string path2 = "C:\Files\audit.txt";
         using (StreamWriter sw2 = File.AppendText(path2))
         {
              sw2.WriteLine("Login Failed: Invaild username or password");
         }
         throw new FileNotFoundException();
 }

您可以读取一个数组中的所有行,然后尝试在该数组中找到您的字符串。

string textToFind = string.Format ("{0} {1} {2}",command,param1,param2)
bool anyHit = File.ReadAllLines (path).Any(x => string.Compare (textToFind,x) == 0));

你的方法看起来像

protected void login(string command, string param1, string param2) // string command "login" string username, string password
{
    if (command == "login")
    {
        var logins = File.ReadAllLines(@"C:\Files\accounts.txt");
        if (logins.Any(l => l == string.Format("{0} {1}", param1, param2)))
            Console.WriteLine("login {0} successful", param1);
        else
        {
            //log audit details
            Console.WriteLine("invaild username/password");
        }
    }
}

正如@Valentin 所说,您可以使用 File.ReadAllLines() 读取文本文件的所有行。

string path = "C:\Files\accounts.txt";
string[] LoginCredentials = File.ReadAllLines(path);
for(i=0;i<LoginCredentials.Length;i++)
{
    //Split Line (Credential[0] = Username, Credential[1] = Password)
    string[] Credential = LoginCredentials[i].Split(' ');

    //Check if input matches
    if(param1 == Credential[0] && param2 == Credential[1])
    {
       Console.WriteLine("username and password match", path); 
    }
}
   // If Input never matched login failed
    Console.WriteLine("Login Failed: invaild username or password");
    string path2 = "C:\Files\audit.txt";
    using (StreamWriter sw2 = File.AppendText(path2))
    {
    sw2.WriteLine("Login Failed: Invaild username or password");
    }
    throw new FileNotFoundException();