我正在创建一个简单的程序,该程序从Customer.txt文件读取用户名和密码,并验证是否正确。 Customer.txt的格式设置为用户名顺序,然后用逗号分隔密码(忽略此练习的安全问题):


  JohnDoe,1234,JaneDoe,5678,...


是否可以创建一个foreach循环以遍历strArray[]并检查对{strArray[0]strArray[1]}然后检查{strArray[2]strArray[3]}等,以查看用户是否输入了正确的凭据?

private void enter_click_Click(object sender, RoutedEventArgs e)
{
    StreamReader reader1 = new StreamReader("Customers.txt");
    string text = reader1.ReadToEnd();
    reader1.Close();

    string[] Strarray = text.Split(',');
    StreamReader reader2 = new StreamReader("Admin.txt");
    string text2 = reader2.ReadToEnd();
    reader2.Close();

    string[] AdminArray = text2.Split(',');
    if (username_txt.Text == AdminArray[0] && passwordBox1.Password == AdminArray[1])
    {
        AdminPage admin = new AdminPage();
        admin.Activate();
        admin.Show();
        method.CheckDate();
        return;
    }
    if (username_txt.Text == Strarray[0] && passwordBox1.Password == Strarray[1])
        {
            ATM_Screen atm = new ATM_Screen();
            atm.Activate();
            atm.Show();
            method.CheckDate();
            return;
        }

最佳答案

是的,您可以这样做:

var usernames = Strarray.Where((s, i) => { return i % 2 == 0; });
var passwords = Strarray.Where((s, i) => { return i % 2 != 0; });

var userPasswords = usernames.Zip(passwords, (l, r) => new { username = l, password = r });
foreach(var userPassword in userPasswords) {
    if (userPassword.username == "rob" && userPassword.password == "robspassword") {

    }
}


根据评论进行编辑:

您可以对多个有效凭据执行此操作:

var allowedCredentials = new List<Tuple<String, String>> {
    new Tuple<String, String>("Rob", "Robspassword"),
    new Tuple<String, String> ("SomeoneElse", "SomeoneElsespassword"
};

var inputCredentials = new List<string> { "Rob","Robspassword","Rob","Notrobspassword" };

var usernames = inputCredentials.Where((s, i) => { return i % 2 == 0; });
var passwords = inputCredentials.Where((s, i) => { return i % 2 != 0; });

var userPasswords = usernames.Zip(passwords, (l, r) => new { username = l, password = r });
foreach(var userPassword in userPasswords) {
    if (allowedCredentials.Any(ac => ac.Item1 == userPassword.username
           && ac.Item2 == userPassword.password)
    {
        //Valid
    }

}

10-08 14:04