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
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 ));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.