简体   繁体   English

如何检查文件中是否已经存在用户名

[英]How can I check if username already exists in the file

In a class, I am entering data to create an account. 在课堂上,我正在输入数据来创建一个帐户。 Now every data that is entered by the user is saved in a file. 现在,用户输入的每个数据都保存在一个文件中。 Now for the Username, I want to check if the username already exists the file. 现在,对于用户名,我想检查用户名是否已存在。 How can I do this? 我怎样才能做到这一点?

      public void CreateAccount()
      {

        Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        Console.WriteLine("Enter a Username: ");

        Client usernameField = new Client("Username")
        {
            UsernameField = Console.ReadLine()
        };


        string filePath = "C:\\createaccount.txt"

        Client.SerializeData(accountData, filePath);

    public static void SerializeData(List<Client> userToSerialize, string 
    filePath)
    {
        FileReadWrite<Client>.SerializeData(userToSerialize, filePath);
    }

    public static List<Client> DeserializeData<Client>(string filePath)
    {
        return FileReadWrite<Client>.DeserializeData<Client>(filePath);
    }  

You need to deserialize the existing data stored in the file. 您需要反序列化存储在文件中的现有数据。

var listOfClients = Client.DeserilizeData(fileName);

This would give you a list of existing users. 这将为您提供现有用户的列表。 Then you can use Linq to check if Username already exists 然后您可以使用Linq检查用户名是否已经存在

var exists = listOfclients.Any(x=>x.UsernameField.Equals(newUserName));

If the user name is case-insensitive, you need to use 如果用户名不区分大小写,则需要使用

var exists = listOfclients.Any(x=>x.UsernameField.Equals(newUserName,StringComparison.OrdinalIgnoreCase));

Update based on your code. 根据您的代码进行更新。

Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine("Enter a Username: ");

Client usernameField = new Client("Username")
{
    UsernameField = Console.ReadLine()
};
var listOfClients = Client.DeserilizeData(fileName);
var exists = listOfclients.Any(x=>x.UsernameField.Equals(usernameField.UsernameField ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM