Search code examples
c#text-files

How to check if password matches username in c# using text files?


I'm a student who just started learning C# and I want to know how to check to see if the password matches the username in a text file.

static void CheckExist()
        { 
            Console.WriteLine("Enter username: ");  //ask the user for the username and store in a variable 
            string EuserName = Console.ReadLine();
            Console.WriteLine("Enter password: "); //ask the user for the password and store in a variable 
            string EpassWord = Console.ReadLine();

            string [] lines = File.ReadAllLines(filename);  //read all lines of the file into an array
            bool UserExist = false;  //declares a Boolean variable to track if the user/password exists
            string[] x;

            foreach (string i in lines)//foreach string in the array
            {
                x = i.Split(","); //split the line on comma and store in an array X
                if (x[0] == EuserName && x[2] == EpassWord)  //if x index 0 equals the username and x index 2 equals the password
                {
                    UserExist = true; // user exists, set the Boolean variable and exit loop
                    break;
                }
            } //end of loop 
            if (UserExist == false)
            {
                Console.WriteLine("User doesn't exist");
            }

            //if the Boolean variable is still false the user didn't exist, otherwise they did

        }

This is the updated code, proved working


Solution

  • Implement the following logic:

    //ask the user for the username and store in a variable 
    //ask the user for the password and store in a variable 
    
    //read all lines of the file into an array
    
    //declare a Boolean variable to track if the user/password exists
    
    //foreach string in the array
    
      //split the line on comma and store in an array X
    
      //if x index 0 equals the username and x index 2 equals the password
    
        // user exists, set the Boolean variable and exit loop
    
    //end of loop 
    
    //if the Boolean variable is still false the user didn't exist, otherwise they did
    

    This is what you should do when you code: write the logic out in the language you think in and then translate it to c#. From the code in your question you already know how to do all the above