Search code examples
c#authenticationmethodsconsole-applicationuser-input

How do I get user input to use my validate method for a login console application?


Basically I want to be able to ask the user the enter their details and from the user input I want to be able to cross check the credentials with data in a text file which I have already setup I am simply just having trouble figuring out a way to use the method and take in the users input.

  static void Main(string[] args)
    {

        Console.WriteLine("PLEASE ENTER CORRECT DETAILS TO LOGIN");
        Console.WriteLine("Enter Username: ");
        Console.ReadLine();
        Console.WriteLine("Enter Password: ");
        Console.ReadLine();
     
    }

Is it possible to get users input to cross check using this method:

    public bool Validate(string username, string password)
    {
        string filePath = @"C:\Users\K\Desktop\Accounts\login.txt";
        string[] logininfo = File.ReadAllLines(filePath + @"C:\Users\K\Desktop\Accounts\login.txt");

        foreach (string detail in logininfo)
        {
            users user = new users(detail);
            if (user.username == username && user.password == password)
            {
                return true;
            }
        }
        return false;
    }

}

Solution

  • You can just store the value you read from the console and pass it to the validate function. Since you are reading a string you don't need any casting. If you are reading a value which is not a string such as Integer, you have to consider type casting.

    int value = Int32.Prase(Console.ReadLine());

    Since you have not do so, this code will solve your problem.

    static void Main(string[] args)
    {
    
        Console.WriteLine("PLEASE ENTER CORRECT DETAILS TO LOGIN");
        
        Console.WriteLine("Enter Username: ");
        var username = Console.ReadLine();
        
        Console.WriteLine("Enter Password: ");
        var password = Console.ReadLine();
        
        var isValid = validate(username, password); 
    }