Click here to Skip to main content
15,886,963 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
the application ask for user name and password. The application matches the login name and password from the already saved login names and their password given in a text file called “login.txt”. If the user name and password are correct then the application { do something ....}


I don't want to use contain, If I wrote in the textfile in this format, username:password, how can replace that instead of contain ???

C#
using (StreamReader sr = File.OpenText("E:\\login.txt"))
               {
                   string[] lines = File.ReadAllLines("E:\\login.txt");

                   {

                       if (lines.Contains(Username) && lines.Contains(Password))
                       {
                          .......
                       }
Posted
Comments
PIEBALDconsult 31-Oct-15 15:52pm    
Better to use XML. And encrypt the password as well.
R.M49 31-Oct-15 15:58pm    
It is required to do it in this way, it is only for practise
BillWoodruff 31-Oct-15 16:12pm    
If we do your homework for you, you will learn nothing.

.Contains is not the problem.
The problem of this code is that, the way you have done it, any string that is in login.txt will match as a username and as a password.
So if Username="a" and Password="a", it will be probably accepted by your code.
To ensure that you match a Username and matching Password, you need to check line by line
C#
foreach (string Line in Lines) {
    // Check Username and password
}

then split the Line in its components.
C#
foreach (string Line in Lines) {
    string[] Parts= Line.Split(",");
    // Check Username and password
}

then check Username with Parts[0] and Password with Parts[1].
C#
UserFound= False;
foreach (string Line in Lines) {
    string[] Parts= Line.Split(",");
    // Check Username and password
    if (Username == Parts[0] && Password == Parts[1]) {
        UserFound= True;
        break;
    }
if (UserFound) {
    // do what you need
}
}
 
Share this answer
 
Comments
BillWoodruff 1-Nov-15 4:20am    
+5 too bad C# .NET doesn't have a native "Near" text matching function.
C#
class Foo
{
    static void Main(string[] args)
    {
        string text = File.ReadAllText("E:\\login.txt");

        string[] temp = text.Trim().Split(':');

        string username = temp[0];
        string password = temp[1];
        
        if(username == Username && password == Password)
        {
           //do stuff
        }
    }
}
 
Share this answer
 
v2
Comments
R.M49 31-Oct-15 15:57pm    
where is the if statement ??? how can I check if it matches the textfile or not

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900