C# Console Application Password Input Checker - c#

The following code has preset passwords that the user must enter to continue the code. However, when the set passwords (PASS1-PASS3) are entered, the code goes to the do-while regardless. What do I need to do in order to make the while recognize that the password is correct so that it does not go to the invalid password line?
// Program asks user to enter password
// If password is not "home", "lady" or "mouse"
// the user must re-enter the password
using System;
public class DebugFour1
{
public static void Main(String[] args)
{
const String PASS1 = "home";
const String PASS2 = "lady";
const String PASS3 = "mouse";
String password;
String Password;
Console.Write("Please enter your password ");
password = Console.ReadLine();
do
{
Console.WriteLine("Invalid password enter again: ");
password = Console.ReadLine();
} while (password != PASS1 || password != PASS2 || password != PASS3);
Console.WriteLine("Valid password");
Console.ReadKey();
}
}

You have your logic the wrong way around i.e. do something then check some conditions, whereas you want to check some conditions and then do something. So the following code:
do
{
Console.WriteLine("Invalid password enter again: ");
password = Console.ReadLine();
} while (password != PASS1 || password != PASS2 || password != PASS3);
Should read:
while (password != PASS1 && password != PASS2 && password != PASS3)
{
Console.WriteLine("Invalid password enter again: ");
password = Console.ReadLine();
}
Notice that I also changed the logical ORs || to logical ANDs &&. this is because you want to check if it is not equal to all of them, not just one.
On a side note the variable Password is unused and should be removed as it can lead to typo errors to your used variable password.

Try changing the "||" to "&&".
It will cannot equal all of them at once.

Related

C# Comparing user input with data from external file C#

Sorry if the post is duplicated, but I couldn't find any case like mine that is posted here or somewhere else.
I am working on a C# console application that should save the user input and then read it again "Something like a simple sign up and login application".
using System;
using System.IO;
namespace Reader
{
class Program
{
static void Main(string[] args)
{
string filepath = #"C:\myProgramingFiles\password.txt";
StreamReader reader = File.OpenText(filepath);
string line = reader.ReadLine();
Console.WriteLine("Write your username:");
string userInput = Console.ReadLine();
Console.WriteLine("Write your password:");
string password = Console.ReadLine();
Console.WriteLine(userInput);
Console.WriteLine(password);
while(line != null)
{
Console.WriteLine(userInput == line);
Console.WriteLine(password == line);
if (userInput == line)
{
Console.WriteLine("Your username is: " + line);
}
if(password == line)
{
Console.WriteLine("Your password is: " + line);
}
line = reader.ReadLine();
}
reader.Close();
}
}
}
I have this code that reads the data from password.txt, and everything works fine, but when I do the if-else it's first checks if both user inputs are the same as the username, and then it loops again and checks if both user inputs are like the password. Sorry if I couldn't make it clear, you can run this code if you want and mock up the password.txt, and check it.
It is actually a logical and expected result, but the thing is that I don't know how else I should do it. Can you please help me?
I have tried a lot of things that didn't work, and this was my last try, so I know that it is not the best code, but it explains the problem
Let's suppose your password.txt file is like this (which appears to be the case):
password.txt
User1
Pass123
User2
Pass456
etc.
The way your code is written, with that loop you have, if the user enters User1 for the username and Pass123 for the password, the output will be:
Your username is: User1
Your password is: Pass123
BUT if the same user enters User1 and Pass456 the output will be:
Your username is: User1
Your password is: Pass456
Which is obviously undesirable logic.
So what you need is to use your loop to check for the matching username, and only when that condition is met, check for the matching password.
Otherwise you even get results like this, if the user enters Pass123 for the username and Pass456 for the password:
Your username is: Pass123
Your password is: Pass456
This can happen because you are not associating the password with the username. To make them connected you would write the code like this, assuming that username and password are on separate lines:
SOLUTION:
while(line != null)
{
Console.WriteLine(userInput == line);
Console.WriteLine(password == line);
if (userInput == line)
{
// ** CHANGES BEGIN
line = reader.ReadLine(); // get password on next line
if (line == password)
{
Console.WriteLine("Credentials are valid");
}
else
{
Console.WriteLine("Credentials are invalid");
}
break; // no need to continue this loop
}
else {
// Important: skip past password line since the username didnt match
line = reader.ReadLine();
}
// ** CHANGES END
line = reader.ReadLine(); // this is now reading the next username or EOF
}
Put the following into your text file:
hello:world
Put the following into your code:
static void Main(string[] args)
{
string filepath = #"C:\myProgramingFiles\password.txt";
Console.WriteLine("Write your username:");
string username = Console.ReadLine();
Console.WriteLine("Write your password:");
string password = Console.ReadLine();
var lines = File.ReadAllLines(filepath);
var usrpwd = username + ":" + password;
foreach(line in lines)
{
if(usrpwd == line)
Console.WriteLine("Credentials accepted");
}
}
Run the app and type hello as the username and world as the password. Build from there ..
When it comes to saving new data in your text file look at File.AppendAllLines or read all your lines in, add new data in memory and then overwrite the whole file. That's probably most easily arranged by having the data in a list, rather than an array:
var lines = new List<string>(File.ReadAllLines(...));
Then you can lines.Add(...) a user:password pair and write it out again

Beginner Question - While loop for simple password program only looping question

I'm following a tutorial to create a simple command prompt program to ask for password (console.writeline) and write that the password is authenticated if inputted correctly (console.readline + if statement) - this runs smoothly:
Console.WriteLine("Please Input Your Password:");
var password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else if (password != "secret")
Console.WriteLine("You have not been authenticated");
The next part of the exercise is to ask for the password to be typed again if it is incorrect. I followed the exercise per the tutorial but upon running the program the program loops the question line after line rather than methodically going through the steps of the code.
var password = "";
while (password !="secret")
Console.WriteLine("Please Input Your Password:");
password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else if (password != "secret")
Console.WriteLine("You have not been authenticated");
Would be grateful for any advice! thanks!
Your while loop is missing curly blocks {}. when not specifing {} you the while loop only specifies to the next line instead of code block you wanted.
Also, you don't need the else if (password != "secret"). else is enough
var password = "";
while (password !="secret")
{
Console.WriteLine("Please Input Your Password:");
password = Console.ReadLine();
if (password == "secret")
Console.WriteLine("You have been authenticated");
else
Console.WriteLine("You have not been authenticated");
}

Looping a password checker in C#?

I'm trying to create a password checker.
My idea was to have a bool return type method with a string parameter which would be the user's input. If the string fulfills all the conditions, the method would return true. Otherwise it should return false and loop from the start (take another input from the user to check the password again).
Problem is, even though I got all the conditions that I wanted to have right, I can't get it to loop every time a condition is false. I've tried to do it with for, etc., but it doesn't seem to work. I assume the problem is in the user input (I'm either putting it somewhere that's wrong or something like that) but at this point I'm out of ideas.
If you have an answer, please explain it to me instead of just giving me some code so I can understand where did I go wrong.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BeginnerProjects
{
class PasswordCreator
{
static void Main(string[] args)
{
string passLengthReq = "Password length should be 8 symbols or more.";
string passUppercaseReq = "Password should contain at least one uppercase letter.";
string passDigitReq = "Password should contain at least one digit.";
Console.WriteLine("Please insert your desired password, the password has the following requirements:");
Console.WriteLine($"{passLengthReq}\n{passUppercaseReq}\n{passDigitReq}");
string chosenPass = Console.ReadLine();
do
{
IsPassCorrect(chosenPass);
Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
static bool IsPassCorrect(string chosenPass)
{
// Checks for Null
if (string.IsNullOrEmpty(chosenPass))
{
Console.WriteLine("Password is empty!");
return false;
}
// Checks for Length
else if (chosenPass.Length < 8)
{
Console.WriteLine($"Your password is too short, it contains {chosenPass.Length} characters!");
return false;
}
// Checks for Number Present
else if (!chosenPass.Any(char.IsNumber))
{
Console.WriteLine("Error, your password doesn't contain a number!");
return false;
}
// Checks for Decimal Present
else if (chosenPass.Any(char.IsDigit))
{
Console.WriteLine("Error, your password contains a decimal!");
return false;
}
// Checks for Uppercase Letter
else if (!chosenPass.Any(char.IsUpper))
{
Console.WriteLine("Error, your password doesn't contain an uppercase letter!");
return false;
}
else
{
Console.WriteLine("Your password is valid!");
return true;
}
}
}
}
}
Take this part:
string chosenPass = Console.ReadLine();
do
{
IsPassCorrect(chosenPass);
Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
And change it to:
string chosenPass;
do
{
chosenPass = Console.ReadLine();
}
while (IsPassCorrect(chosenPass) == false);
Now the loop will always prompt the user before checking the password, and keep doing so until IsPassCorrect(chosenPass) returns true.
You can simplify IsPassCorrect(chosenPass) == false if desired:
string chosenPass;
do
{
chosenPass = Console.ReadLine();
}
while (!IsPassCorrect(chosenPass));

How would I make a Yes/No prompt in Console using C#?

I'm mostly new to C# and I've been writing code to practice.
I've written some code where you enter a line of text, or a "login key", and I want to make it where you can confirm that login key.
Here's the code I've done so far, I will use "//" on the part I'm stuck on. (Wont include any unnecessary code.)
Console.WriteLine("Please enter a login key.");
string Key = Console.ReadLine();
Console.WriteLine("You entered, " + Key + " as your login key!");
Console.WriteLine("Are you sure you want to choose this as your login key? "); // This is where I'm stuck at, got no idea how to do a yes/no prompt.
}
Any help would be greatly appreciated.
You can easily go overboard on these Console login scripts. Here's my contribution:
bool confirmed = false;
string Key;
do {
Console.Write("Please enter a login key: ");
Key = Console.ReadLine();
Console.WriteLine("You entered, " + Key + " as your login key!");
ConsoleKey response;
do
{
Console.Write("Are you sure you want to choose this as your login key? [y/n] ");
response = Console.ReadKey(false).Key; // true is intercept key (dont show), false is show
if (response != ConsoleKey.Enter)
Console.WriteLine();
} while (response != ConsoleKey.Y && response != ConsoleKey.N);
confirmed = response == ConsoleKey.Y;
} while (!confirmed);
Console.WriteLine("You chose {0}!", Key);
Console.ReadLine();
Sample output:
Please enter a login key: potato
You entered, potato as your login key!
Are you sure you want to choose this as your login key? [y/n] a
Are you sure you want to choose this as your login key? [y/n] s
Are you sure you want to choose this as your login key? [y/n] l
Are you sure you want to choose this as your login key? [y/n] d
Are you sure you want to choose this as your login key? [y/n] k
Are you sure you want to choose this as your login key? [y/n] f
Are you sure you want to choose this as your login key? [y/n] d
Are you sure you want to choose this as your login key? [y/n] n
Please enter a login key: banana
You entered, banana as your login key!
Are you sure you want to choose this as your login key? [y/n] y
You chose banana!
I remake it like a utils class I hope it's gonna be usefull:
class UtilsConsole
{
public static bool Confirm(string title)
{
ConsoleKey response;
do
{
Console.Write($"{ title } [y/n] ");
response = Console.ReadKey(false).Key;
if (response != ConsoleKey.Enter)
{
Console.WriteLine();
}
} while (response != ConsoleKey.Y && response != ConsoleKey.N);
return (response == ConsoleKey.Y);
}
}
Use Console.ReadKey();
Console.WriteLine("Press 'y' if you would like awesome!");
ConsoleKeyInfo cki = Console.ReadKey();
if (cki.Key.ToString() == "y")
{
//do what you need for yes
}else {
// presses something other then Y
}
I prefer to create a reusable method to handle all future questions. Very simplified version to illustrate basics.
void Main(string[] args)
{
if(PromptConfirmation("Did you answer yes?"))
{
//todo: Handle positive response
}
}
private bool PromptConfirmation(string confirmText)
{
Console.Write(confirmText + " [y/n] : ");
ConsoleKey response = Console.ReadKey(false).Key;
Console.WriteLine();
return (response == ConsoleKey.Y);
}
You can use a while loop
bool confirmed = false;
while(!confirmed)
{
Console.WriteLine("Please enter a login key.");
string Key = Console.ReadLine();
Console.WriteLine("You entered, " + Key + " as your login key!");
Console.WriteLine("Are you sure you want to choose this as your login key? [yes/no]");
string option = Console.ReadLine();
if (option == "yes")
{
confirmed = true;
}
}
This way if option is anything but yes it will remain in the while loop.

VS2015 C#, How do I get the login form to reference usernames and passwords for authentication

Newbie coder here.
I want to make an application which is a simple windows form which is a login window. Using array to reference the login username and password.
So far this is what I've gotten. And seem to have encountered an error with the code. I can't seem to figure it out.
The code gives me an error saying that Represents a boolean (true or false) value.
Image of the code: http://i.stack.imgur.com/uvmtP.png
private void btnLogin_Click(object sender, EventArgs e)
{
string[] Username = { "user1", "user2", "user3" };
string[] Password = { "Password1", "Password2", "Password3" };
if (Username[0].ToString() == Password[0])
this.Close();
th = new Thread(opennewform);
th.SetApartmentState(ApartmentState.STA);
th.Start();
if ((txtPasswd.Text == Username) && (txtUser.Text == Password))
{
Success_Login Success = new Success_Login();
Success.Show();
}
else
MessageBox.Show("Enter valid username and/or password");
}
}
Many thanks.
wow what you try to do?
i see 2 error first one
you try compare your username text with the password for validation
it make no sence
then you try to evaluate an equality between an array of string and a simple string.
so correct this first for get answer
to me you
try to do something like
if(username[0] == txtuser.text && Password[0] == txtpassword.text)
{
// then your first user can login
}
but its not how we do a login in c#
password can't be stored in code since the code can be read easily.
Username and Password are string arrays you need to use Array.Contains or Array.IndexOfto check if TextBox values exists in those arrays.
if(Array.Contains(Username, txtUser.Text) && Array.Contains(Password, Password.Text))
{
}
Or use IndexOf
if(Array.IndexOf(Username, txtUser.Text) != -1 && Array.IndexOf(Password, txtPassword.Text)!= -1)
{
}
I think you need a for loop to check for each username and password.
Let me write a stupid simple program but workable of login process.
My output:
User=user1, Password=abc login failed!!
User=user2, Password=xxx login failed!!
User user2 login success!!
User user1 login success!!
My source code:
using System;
namespace sam_StreamReader
{
class Program
{
static void Main(string[] args)
{
login("user1", "abc");
login("user2", "xxx");
login("user2", "Password2");
login("user1", "Password1");
}
static bool login(string p_user_name,string p_password)
{
String[] Username = { "user1", "user2", "user3" };
String[] Password = { "Password1", "Password2", "Password3" };
for(int i=0;i<Username.Length;i++)
{
if(p_user_name == Username[i])
{
if(p_password == Password[i])
{
System.Console.WriteLine("User "+p_user_name+" login success!!");
return true;
}
}
}
System.Console.WriteLine("User=" + p_user_name + ", Password="+p_password+" login failed!!");
return false;
}
}
}
Hope this helps~

Categories

Resources