C# Visual Studio - Implementing user authentication using text files - c#

Using visual studio 2013 and Console Application.
My question, How to I make something like this: I have a programm. I want the programm to check if there is a file called Usernames.txt, If there is,do nothing and if there is not, Create a new one.
Now when that Is done, I want the console to ask the person to enter a username, When the person does it, I want the programm to check if the file called: Usernames.txt contains that same username that the person entered, If yes, Then tell the person: This username already exists, Pick a new one. If not then add it to the file and continue on to ask for a password and so on.
This is what I got so far and I don't know what to do next:
Console.WriteLine("Username: ");
string uCreation = Console.ReadLine();
bool exists = false;
foreach (string lines in File.ReadAllLines("Usernames.txt"))
{
if (lines == uCreation)
{
Console.WriteLine("Username already exists!");
exists = true;
break;
}
}
if (!exists)
{
File.AppendAllText(#"Usernames.txt", uCreation + Environment.NewLine);
}
Am I on the right track? I have no idea D= If anybody could help out with some solutions that would be sweet!
Thanks!

You should be able to modify this code to suit your requirements.
class Program
{
static void Main(string[] args)
{
try
{
if (File.Exists(#"c:\Usernames.txt"))
{
Console.WriteLine("File already exists.I am doing nothing.Tadaaaaaaaaaa !!!");
return;
}
else
{
string sContinue = "yes";
HashSet<string> sUserNames = new HashSet<string>();
while (sContinue.Equals("yes"))
{
Console.WriteLine("Enter username:");
string sUserName = Console.ReadLine();
if (!sUserNames.Contains(sUserName))
{
sUserNames.Add(sUserName);
using (StreamWriter oWriter = new StreamWriter(#"c:\Usernames.txt", true))
oWriter.WriteLine(sUserName);
Console.WriteLine("Username {0} was added.Enter yes to continue or no to exit", sUserName);
}
else
Console.WriteLine("Username {0} exists.Enter yes to add new username or no to exit", sUserName);
sContinue = Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Done");
Console.Read();
}
}

Here is your solution :
static void Main()
{
string path = #"C:\Usernames.txt";
if (File.Exists(path))
Console.WriteLine("File already exists. Exiting the application...");
else
{
List<string> list = new List<string>();
string IsContinue = "Y";
while (IsContinue.Equals("Y"))
{
Console.WriteLine("Enter the username --");
string userName = Console.ReadLine();
if (!list.Contains(userName))
{
list.Add(userName);
File.AppendAllText(path, userName + Environment.NewLine);
Console.WriteLine("Success...! Continue (Y/N) ?", userName);
IsContinue = Console.ReadLine().ToUpper();
}
else
Console.WriteLine("{0} already exists. Choose a new Username again.\n", userName);
}
}
}
....................................

Related

C# Login error with text checking/validation

So baiscally my first registered username and password in my text file when i login is able to pass through the validation however my next pair gets past the .contains but fails at checking password, not giving me the message and closing the console.
Example of text file-
Elliot|Benten67Fred|Payne
It will be able to check Elliot and Benten67. However can locate Fred but not able to check if the password is right? Any help would be great
public void Register()
{
string filePath = #"/Users/elliot/Documents/Film Libary Software/Film-Libary/Film-Libary/bin/Debug/netcoreapp3.1/UserInfo.txt";
Console.WriteLine("Create A Username which contains A Upper Case character");
Username = Console.ReadLine();
bool usernameIsUpper = Username.Any(char.IsUpper);
if (usernameIsUpper)
{
Console.WriteLine("Please enter a password: ");
Password = Console.ReadLine();
string toWrite = Username + "|" + Password;
File.AppendAllText(filePath, toWrite);
Login();
}
else
{
Console.WriteLine("Invalid Username: Please try again!");
Register();
}
}
public void Login()
{
string fileName = #"/Users/elliot/Documents/Film Libary Software/Film-Libary/Film-Libary/bin/Debug/netcoreapp3.1/UserInfo.txt";
using (StreamReader reader = new StreamReader(fileName))
{
string line;
Console.WriteLine("Enter your username");
string loginUsername = Console.ReadLine();
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(loginUsername))
{
int indexOfDelimiter = line.IndexOf('|');
string usernameFromFile = loginUsername;
string passwordFromFile = line.Substring(indexOfDelimiter + 1, line.Length - (indexOfDelimiter + 1));
Console.WriteLine("Please enter your password");
string enteredPassword = Console.ReadLine();
if (enteredPassword == passwordFromFile)
{
Console.WriteLine("Elliot well done");
}
}
}
}
}
Your reading code requires the each user be on a separate line, but you are not writing new lines, you can see that here
Elliot|Benten67Fred|Payne
you need
Elliot|Benten67
Fred|Payne
The error is here
string toWrite = Username + "|" + Password;
File.AppendAllText(filePath, toWrite);
you need
string toWrite = Username + "|" + Password + "\n";
File.AppendAllText(filePath, toWrite);

How would I program my code to start over if a certain condition is met?

For clarification I'm using Microsoft visual studio and trying to turn the cmd format into a cute little interactive terminal. I'm a bare basics beginner and I'm aware this may be an ambitious project for someone of my skill. The only thing I'm confused about at the moment is how to tell the program that I want it to start itself over within the constraints of an else if statement.
static void Main(string[] args)
{
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
if (val == "yes")
{
Console.WriteLine("Data confirmed, thank you for your cooperation!");
}
else if (val == "no")
{ //I would like to restart the code if this condition is met
Console.WriteLine("Incorrect data provided, please try again");
}
else
{ //The issue with this line is that I want it to just ask if the data is correct again
Console.WriteLine("That is not a valid response, try answering with a yes or no");
}
Try something like this. Basically, you're wrapping your code in a loop (in this case, a "do...while" loop, and adding a flag indicating whether or not the program should "start over."
static void Main(string[] args)
{
bool finished;
do
{
finished = true;
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
while(val != "yes" && val != "no") {
Console.WriteLine("That is not a valid response, try answering with a yes or no");
val = Console.ReadLine();
}
if (val == "yes") {
Console.WriteLine("Data confirmed, thank you for your cooperation!");
}
else if (val == "no") {
Console.WriteLine("Incorrect data provided, please try again");
finished = false;
}
} while(!finished);
}
You can break your code out into a separate method, and call it from your Main() method. Then, in your else statement, you can have your new method call itself so that it executes again. (Disclaimer: It's been a long time since I've written C#.)
static void Main(string[] args) {
askName();
}
static void askName() {
Console.WriteLine("What's your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("What's your age?");
string age = Console.ReadLine();
Console.WriteLine("Your name is " + name + " and you are " + age + " years old, Correct?");
string val = Console.ReadLine();
if (val == "yes") {
Console.WriteLine("Data confirmed, thank you for your cooperation!");
} else if (val == "no") {
askName();
} else {
//The issue with this line is that I want it to just ask if the data is correct again
Console.WriteLine("That is not a valid response, try answering with a yes or no");
}
}

Gurobi does not recognize LP file

When trying to open a Linear Programming problem from text with Gurobi+C# it throws the error: 10012 Unable to open file "Maximize" for input.
Maximise is the first word of the text and when using
foreach (string s in args)
{
Console.WriteLine(s);
}
i get the correct output from the text file. Please help!
using System;
using Gurobi;
class lp_cs
{
static void Main(string[] args)
{
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
foreach (string s in args)
{
Console.WriteLine(s);
}
if (args.Length < 1)
{
Console.Out.WriteLine("Please Wait..");
return;
}
try
{
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Optimize();
int optimstatus = model.Get(GRB.IntAttr.Status);
if (optimstatus == GRB.Status.INF_OR_UNBD)
{
model.GetEnv().Set(GRB.IntParam.Presolve, 0);
model.Optimize();
optimstatus = model.Get(GRB.IntAttr.Status);
}
if (optimstatus == GRB.Status.OPTIMAL)
{
double objval = model.Get(GRB.DoubleAttr.ObjVal);
Console.WriteLine("Optimal objective: " + objval);
}
else if (optimstatus == GRB.Status.INFEASIBLE)
{
Console.WriteLine("Model is infeasible");
model.ComputeIIS();
model.Write("model.ilp");
}
else if (optimstatus == GRB.Status.UNBOUNDED)
{
Console.WriteLine("Model is unbounded");
}
else
{
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
}
model.Dispose();
env.Dispose();
}
catch (GRBException e)
{
Console.WriteLine("Hibakód: " + e.ErrorCode + ". " + e.Message);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
you are overwriting the args parameter of your main() method with an array of all lines of the input file. That's why in
GRBModel model = new GRBModel(env, args[0]);
args[0] contains a string with the first line of your LP file instead of the filename.

Prevent empty console input from user in c#

Hi I would like to prevent users from entering nothing in the input field.
I've tried using an if else but the console keeps crashing when there's no input. (for both user input and ldap address input ==> I want it to show "No input detected." and allow the user to re-enter the username)
And if I used (results == " "), I would get a error:
"Operator '==' cannot be applied to operands of type
'System.DirectoryServices.SearchResult' and 'string'"
Is there any way for me to resolve this? The codes are as shown below.
Affected codes from line 16 onwards (for the top block of codes)
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived)
Console.WriteLine(targetUserName + "'s account is active.");
else
Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked)
Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else
Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
If it helps, I've attached the whole code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Program
{
const String serviceAccountUserName = "mobileuser1";
const String serviceAccountPassword = "password123$";
const int UF_LOCKOUT = 0x0010;
const int UF_PASSWORD_EXPIRED = 0x800000;
static void Main(string[] args)
{
string line;
Console.WriteLine("Welcome to account validator V1.0.\n"+"Please enter the ldap address to proceed.");
Console.Write("\nEnter address: ");
String ldapAddress = Console.ReadLine();
try
{
if (ldapAddress != null)
{
Console.WriteLine("\nQuerying for users in " + ldapAddress);
//start of do-while
do
{
Console.WriteLine("\nPlease enter the user's account name to proceed.");
Console.Write("\nUsername: ");
String targetUserName = Console.ReadLine();
bool isValid = false;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
// validate the credentials
isValid = pc.ValidateCredentials(serviceAccountUserName, serviceAccountPassword);
// search AD data
DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapAddress, serviceAccountUserName, serviceAccountPassword);
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(entry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + targetUserName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived) Console.WriteLine(targetUserName + "'s account is active.");
else Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked) Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
}//end of using
}//end of do
//leave console when 'bye' is entered
while ((line = Console.ReadLine()) != "bye");
}//end of if for ldap statement
else if (ldapAddress == " ")
{
Console.WriteLine("No input detected.");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
else
{
Console.WriteLine("Address not found!");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
}//end of try
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
} //end of main void
static private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null) return false;
int flags = (int)de.Properties["userAccountControl"].Value;
return !Convert.ToBoolean(flags & 0x0002);
}
static private bool IsAccountLockOrExpired(DirectoryEntry de)
{
string attribName = "msDS-User-Account-Control-Computed";
de.RefreshCache(new string[] { attribName });
int userFlags = (int)de.Properties[attribName].Value;
return userFlags == UF_LOCKOUT || userFlags == UF_PASSWORD_EXPIRED;
}
}
}
You should put the ReadLine in a loop.
string UserName = "";
do {
Console.Write("Username: ");
UserName = Console.ReadLine();
if (!string.IsNullOrEmpty(UserName)) {
Console.WriteLine("OK");
} else {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(UserName));
You basically repeat the prompt over and over until the string entered by the user is no longer null or empty.
Best method would probably be to create a new function to get a non empty input:
private static string GetInput(string Prompt)
{
string Result = "";
do {
Console.Write(Prompt + ": ");
Result = Console.ReadLine();
if (string.IsNullOrEmpty(Result)) {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(Result));
return Result;
}
You can then just use the function to get your inputs like:
static void Main(string[] args)
{
GetInput("Username");
GetInput("Password");
}
Result:
Try using the code :
(!string.IsNullOrEmpty(input));
This is user first name and last name string
//Make container for the user first name and last name
string myFirstName = "";
string myLastName = "";
//Do while loop
do
{
//Welcomes user to the app and asks for first name then asks for last name
Console.WriteLine("Welcome");
Console.WriteLine("Enter first name: ");
//Takes users first name and last name and saves it in myFirstName and myLastName
myFirstName = Console.ReadLine();
Console.Write("Enter Last name: ");
myLastName = Console.ReadLine();
Console.WriteLine();
//If the first AND (&&) last name is not empty because the user entered first name and last name then display the hello message
if (!string.IsNullOrEmpty(myFirstName) && !string.IsNullOrEmpty(myLastName))
{
Console.WriteLine("Hello " + myFirstName + " " + myLastName + " hope you enjoy your day");
}
else //Else the first name or last name is left empty then display the error message
{
Console.WriteLine("Please enter your first name and last name");
Console.WriteLine();
}
//While if either the first name OR (||) last name is empty then keep asking the user for input
} while (string.IsNullOrEmpty(myFirstName) ||
string.IsNullOrEmpty(myLastName));
Console.ReadLine();
Output:

Create a stream reader in c# console to read only one student at a time instead of all of them using a .txt file

class Program
{
static string strFile = "Student Database.txt";
static void Main(string[] args)
{
string strInput = null; // user input string
start:
System.IO.DirectoryInfo dir = new DirectoryInfo("student_results.txt");
// Request user input as to actions to be carried out
Console.WriteLine("\nWhat do you want to do?\n" +
" 1.View Student(s)\n 2.Add a New Student\n 3.Exit program");
// Save user input to make decision on program operation
strInput = Console.ReadLine();
// Switch statement checking the saved user input to decide the action
// to be carried out
switch (strInput)
{
case "1": // choice for view file
Console.Clear();
string file = AppDomain.CurrentDomain.BaseDirectory +
#"student_results.txt";
StreamReader sr = new StreamReader(file);
string wholeFile = sr.ReadToEnd();
Console.Write(wholeFile + "");
sr.Close();
goto start;
...
}
...
}
...
}
I want this part of my code to just read the students indivially and relay them back to me, instead of how it is doing so at the moment were it just calls all of them back to me when I press '1) view Student' it pretty much says "please enter the students name or ID number of which student you would like to view".
I've currently have got the ID number running off a random number generator.
Thank you for your time guys.
Welcome to SO, first of all goto is not a good choice in C# in 99% of cases, and you'd better use loops. For your code I would save each student in a single line and at the time of reading students I would read them line by line untill I found the student.
class Program
{
static string strFile = "Student Database.txt";
static void Main(string[] args)
{
string strInput = ""; // user input string
while (strInput != "3")
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("student_results.txt");
Console.WriteLine("\nWhat do you want to do?\n 1.View Student(s)\n 2.Add a New Student\n 3.Exit program"); // request user input as to actions to be carried out
strInput = Console.ReadLine(); //save user input to make decision on program operation
switch (strInput)
{
case "1":
Console.Clear();
Console.WriteLine("Enter Student ID: \n");
string file = AppDomain.CurrentDomain.BaseDirectory + #"student_results.txt";
StreamReader sr = new StreamReader(file);
string StudentID = Console.ReadLine();
string line = "";
bool found = false;
while((line = sr.ReadLine()) != null)
{
if (line.Split(',')[0] == StudentID)
{
found = true;
Console.WriteLine(line);
break;
}
}
sr.Close();
if (!found)
{
Console.WriteLine("Not Found");
}
Console.WriteLine("Press a key to continue...");
Console.ReadLine();
break;
case "2":
Console.WriteLine("Enter Student ID : ");
string SID = Console.ReadLine();
Console.WriteLine("Enter Student Name : ");
string SName = Console.ReadLine();
Console.WriteLine("Enter Student Average : ");
string average = Console.ReadLine();
string wLine = SID + "," +SName+":"+average;
file = AppDomain.CurrentDomain.BaseDirectory + #"student_results.txt";
StreamWriter sw = File.Exists(file) ? File.AppendText(file) : new StreamWriter(file);
sw.WriteLine(wLine);
sw.Close();
Console.WriteLine("Student saved on file, press a key to continue ...");
Console.ReadLine();
Console.Clear();
break;
case "3":
return;
default:
Console.Clear();
Console.WriteLine("Invalid Command!\n");
break;
}
}
}
}
this code might not be complete, I wanted to give you the idea, I hope it helps.
Presuming you are not dealing with a huge file of students, and on the basis that you want to make multiple queries, i would not read the text file line by line each time.
Instead create a student class, read the file once on init, and create a list< student > from the data. Then you can query it with LinQ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ReadStudents
{
class Program
{
static string _filename = "students.txt";
static void Main(string[] args)
{
List<Student> students = new List<Student>();
// Load students.
StreamReader reader = new StreamReader(_filename);
while (!reader.EndOfStream)
students.Add( new Student( reader.ReadLine()));
reader.Close();
string action;
bool showAgain = true;
do
{
Console.WriteLine("");
Console.WriteLine("1. See all students.");
Console.WriteLine("2. See student by ID.");
Console.WriteLine("3. Add new student.");
Console.WriteLine("0. Exit.");
Console.WriteLine("");
action = Console.ReadLine();
switch (action)
{
case "1":
foreach (Student item in students)
item.Show();
break;
case "2":
Console.Write("ID = ");
int id = int.Parse( Console.ReadLine() ); // TODO: is valid int?
foreach (Student item in students)
if (item.Id == id)
item.Show();
break;
case "3":
Console.WriteLine("ID-Name");
Student newStudent = new Student(Console.ReadLine());
students.Add(newStudent);
StreamWriter writer = new StreamWriter(_filename, true);
writer.WriteLine(newStudent);
writer.Close();
break;
case "0":
Console.WriteLine("Bye!");
showAgain = false;
break;
default:
Console.WriteLine("Wrong action!");
break;
}
}
while (showAgain);
}
}
class Student
{
public int Id;
public string Name;
public Student(string line)
{
string[] fields = line.Split('-');
Id = int.Parse(fields[0]);
Name = fields[1];
}
public void Show()
{
Console.WriteLine(Id + ". " + Name);
}
}
}
I assume your data are in "ID-Name" format for example:
1-Alexander
2-Brian
3-Christian
I load file line-by-line and pass to Student class which converts in constructor text data to more friendly form. Next, application shows interface until user write "0".

Categories

Resources