Reading strings from a text file - c#

So I'm basically trying to make simple login or register console app but I think I can't open the text file because everytime I enter the correct username it closes the app.This is the code which I think should work.
Console.WriteLine("Username:");
string userNameN = Console.ReadLine();
string username = System.IO.File.ReadAllText(#"C:\test.txt");
if (username == userNameN)
{
Console.Clear();
Console.WriteLine("Correct username");
}
else
{
Console.WriteLine("Incorrect username program will close");
System.Threading.Thread.Sleep(1000);
Environment.Exit(0);
}
System.Threading.Thread.Sleep(1000);

It is happening because execution of code is ended. If you want to wait till next input then add Console.ReadLine(); after Console.WriteLine("Correct username");
Now it will wait till next user input.

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");
}

exit console app after completing process

Hello my console app is for downloading html files and then sending it to a txt file, after the process is complete I would like the app to verify if the file was created and then close the program after telling the user that the page downloaded. I would like to ask how to verify if file exists and then how to exit the app.
Console.WriteLine("Enter a Valid Webpage URL such as http://wwww.google.com, this tool will download the HTML into a .txt file");
string webPage = Console.ReadLine();
Uri uriResult;
bool result = Uri.TryCreate(webPage, UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
WebClient client = new WebClient();
//DownloadsWebpage
string reply = client.DownloadString(webPage);
Console.WriteLine(reply);
//Location of file here
Console.WriteLine("Please enter a valid address to save the .txt file such as C:\\Users\\Public\\String.txt, then press any button to exit");
string txtDir = Console.ReadLine();
File.WriteAllText(txtDir, reply);
Console.ReadLine();
For verifying a file exists, there is a method called File.Exists() which would tell you if it has been created. Then once your program gets to the end of main it will just edit automatically.
Something like the following after your File.WriteAllText(txtDir, reply); may be:
if (!File.Exists(txtDir)) {
Console.WriteLine("Some error creating file");
}
When you want to exit, just let you program close when it reaches the end of main or use Enviroment.Exit(0)
To check if the file Exists and exit:
if( System.IO.File.Exists(pathname))
{
System.Environment.Exit(0);
}
// Do something else here to recover

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.

How to stop program executing further in C#

string FirstName = Console.ReadLine();
if (FirstName.Length > 12)
{
Console.WriteLine(".......................................");
}
if(FirstName.Length<3)
{
Console.WriteLine("....................");
}
Console.WriteLine("...................");
string SecondName = Console.ReadLine();
if (SecondName.Length > 12)
{
Console.WriteLine(".............................");
}
if(SecondName.Length<3)
{
I want to stop the program if they press enter without putting a value,how to do it??/?
string key = Console.ReadKey().ToString(); //Read what is being pressed
if(key == "") {
Console.WriteLine("User pressed enter!");
return; //stop further execution
}
I think you want to have a non empty string value as an input from console and if input is empty then want to terminate your application. Use following code:
Console.WriteLine("Enter a value: ");
string str = Console.ReadLine();
//If pressed enter here without a value or data, how to stop the program here without
//further execution??
if (string.IsNullOrWhiteSpace(str))
return;
else
{
Console.WriteLine(string.Format("you have entered: '{0}'", str));
Console.Read();
}
If user will enter any kind of empty string or white spaces, the application will be terminated the moment he/she will press enter.
Console.ReadLine() returns a string. If nothing is typed and the human just presses the enter key, we'll get an empty string.
There are a number of ways to test whether a string is "empty" for various definitions of empty. Some common definitions of empty and how to test for them:
non-null and containing no data: myString.Length == 0
null or containing no data: string.IsNullOrEmpty(myString)
null, empty, or just whitespace: string.IsNullOrWhiteSpace(myString)
Environment.Exit() will end the process with the exit code you specify.
Combine one of the tests above with Environment.Exit() (and probably an if) and you can stop the process when there's no "value or data".
Also note, that returning from Main is another way to exit the process.

Categories

Resources