Wrong username and password C# - c#

I'm new to C#, and trying to make user login window.
Currently I'm trying to search from txt file and it works fine if I enter correct username. But the issue is when wrong username is entered- it stucks in loop.
Actually the way I'm reading the string from textbox is wrong, Its not allowing me to enter new string before again comparing it from file if I enter wrong username. It keeps comparing the old value or null value
Can anyone guide how this is done?
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
if (lines[us] == usernam)
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?",
"Retry",
MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
username.Clear();
}
}
}

while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
if (lines[us] == usernam)
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
The problem lies in your while loop. Imagine line = "incorrectUsername" on the first iteration of your file. You're assigning "incorrectUserName" to line[0] then line[1] then line[2] etc... and it never stops. You just keep assigning an invalid username into an array then comparing the entered username against that value. What you want to do is ditch the "lines" array, and simply compare the username against the line:
if (line.Equals(username))
{
//Go to new form
}

In this simple case you don't need to use StreamReader, this is a simpler approach:
string myUserName = "Admin";
string[] lines = File.ReadAllLines(usersTextFile, Encoding.UTF8);
bool found = false;
if (lines != null)
{
foreach (var l in lines)
{
if (string.IsNullOrEmpty(l))
continue;
if (l.ToLower() == myUserName.ToLower())
{
found = true;
break;
}
}
}
if (found)
MessageBox.Show("Welcome " + myUserName + "!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
else
MessageBox.Show("User not found!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Error);

My complete code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Employees_1
{
public partial class Form2 : Form
{
string pathuser = #"//192.168.1.10/Shared-Public/testfile.txt";
int check = 0;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
// string username = username.Text;
}
private void button1_Click(object sender, EventArgs e)
{
//string usernam = username.Text;
// MessageBox.Show(usernam);
while (check != 1)
{
userpass();
}
this.Close();
}
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null)
{
lines[us] = line;
if (lines[us] == usernam)
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?", "Retry", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
//DialogResult result = MessageBox.Show("Invalid Username or Password", "Error", MessageBoxButtons.OK);
// MessageBox.Show("Invalid Username or Password");
username.Clear();
}
}
}
/* string[] lines = File.ReadAllLines(pathuser, Encoding.UTF8);
bool found = false;
string usernam = username.Text;
if (lines != null)
{
foreach (var l in lines)
{
if (string.IsNullOrEmpty(l))
continue;
if (l.ToLower() == usernam.ToLower())
{
found = true;
break;
}
}
}
if (found)
MessageBox.Show("Welcome " + usernam + "!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
else
MessageBox.Show("User not found!", "Protected", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
*/
}
}

Related

program shifts data to the right by 1

My code below appends a period to the end of a character entered but each time it shifts the data by 1 extra space to the right. How would I get back that space? The program is very space sensitive
private void button1_Click(object sender, EventArgs e)
{
string stringToReplace = textBox1.Text;
if (stringToReplace.Length == 0)
{
MessageBox.Show("Please enter a valid string.");
return;
}
if (stringToReplace.Length != 6)
{
MessageBox.Show("Please enter a valid string that is 6 characters in length.");
return;
}
OpenFileDialog filedialog = new OpenFileDialog();
DialogResult result = filedialog.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string filePath = filedialog.FileName;
try
{
int counter = 0;
List<string> lines = new List<string>();
System.IO.StreamReader file = new System.IO.StreamReader(filePath);
string line;
while ((line = file.ReadLine()) != null)
{
if (counter == 0 && !line.Contains(stringToReplace+ "."))
{
line = line.Replace(stringToReplace, stringToReplace + ".");
}
counter++;
lines.Add(line);
}
file.Close();
string ext = Path.GetExtension(filePath);
string newFilename = filePath.Replace(ext, "-new" + ext);
System.IO.File.WriteAllLines(newFilename, lines.ToArray());
MessageBox.Show("Process is completed.");
}
catch (IOException)
{
MessageBox.Show("We apologize but an error occured can you try again?");
}
}
}
This screenshot shows how the file should look after the program executes:
The below screenshot shows how it looks how the initial program executes:
As you can see it shifted by one.

How to load paths into ListBox and afterwards start the file per selected Index

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdAdd_Click(object sender, EventArgs e)
{
OpenFileDialog OP = new OpenFileDialog();
OP.Title = "Please select the wanted .exe";
string FileName = String.Empty;
string PathName = String.Empty;
OP.InitialDirectory = #"C:\Users\" + Environment.UserName.ToString() + #"\Desktop";
OP.DefaultExt = ".exe";
OP.Filter = "Game executable (*.exe) |*.exe";
DialogResult Ergebnis = OP.ShowDialog();
if (Ergebnis == DialogResult.OK)
{
FileInfo File = new FileInfo(OP.FileName);
if (File.Exists)
{
PathName = File.FullName;
}
}
if (PathName != String.Empty)
{
textBox1.Text = PathName;
listBox1.Items.Add(PathName);
}
}
private void cmdStart_Click(object sender, EventArgs e)
{
string SelectedItem = "";
if (listBox1.SelectedItem != null)
{
SelectedItem = listBox1.SelectedItem.ToString();
/*MessageBox.Show(SelectedItem);*/
}
Process Pro = new Process();
Pro.StartInfo.FileName = SelectedItem;
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
{
try
{
Pro.Start();
}
catch (Exception)
{
MessageBox.Show("The Start of the Program was aborted!\r\nOr you didn't specify the right Path!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void cmdSave_Click(object sender, EventArgs e)
{
StreamWriter SaveFile = new StreamWriter(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}
SaveFile.Close();
MessageBox.Show("EZPZ");
}
private void cmdLoad_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
string line = string.Empty;
try
{
line = sr.ReadLine();
while (line != null)
{
this.listBox1.Items.Add(line);
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
sr.Close();
}
}
}
Hello Stackoverflow-Community,
So i've tried to be able to start the selected File(from the Listbox) by clicking the Start button.The items in the Listbox are loaded in from a .txt-File, But it seems that the path that i get (from the .txt-File) is not actually the same that was written inside.
For example: H:\Exe\556689600.exe is written inside the .txt-File but when i check while pausing the application the value of the SelectedItem is "H:(two backslashes)Exe(two backslashes)556689600.exe" so i'd like it to be H:\Exe\556689600.exe so it can be properly started.
EDIT: The main problem is that i can't start the .exe that i selected (via cmdStart) and i don't know why.
Please keep in mind that i'm (as you can see from the code) not very experienced in programming and that i'm not an native english speaker, so pardon me for any grammatical mistakes/logic mistakes made.
Thanks in advance,
Stephen
The problem is with:
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
DialogResult holds the Enum data 'DialogResult.Yes', so you need to compare it to that value, and not (true).
Edit:
I suggest practicing working with debug:
In this case, I plated a breakpoint on the 'cmdstart_Click' method and followed it step by step (Used F10)
I saw that we jump over the 'if' condition, and checked why.

Search a record before saving it

I'm developing a simple inventory program that store the hardware devices using C# sql
In my program before I save the record, I want to search for serial number if it exist before I save it or add it in my records to avoid the duplicate, and I receive this exception error:
Syntax error: Missing operand after 'No' operator
Below is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlServerCe;
namespace DataBaseApplication
{
public partial class Form1 : Form
{
#region Fields
SqlDataAdapter dataAdapter;
DataSet ds;
// DataRowView drView;
CurrencyManager crmng;
SqlConnection con;
ToolTip tootip;
int inc = 0;
#endregion
public Form1()
{
InitializeComponent();
}
#region Connetion to the DataBase and fill the DataSet Table
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'impiDbDataSet1.Impi' table. You can move, or remove it, as needed.
//this.impiTableAdapter1.Fill(this.impiDbDataSet1.Impi);
// TODO: This line of code loads data into the 'impiDbDataSet.Impi' table. You can move, or remove it, as needed.
//this.impiTableAdapter.Fill(this.impiDbDataSet.Impi);
try
{
string conStrings = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\ImpiDb.mdf;Integrated Security=True;Connect Timeout=30";
string sql = "Select * from Impi";
con = new SqlConnection(conStrings);
con.Open();
dataAdapter = new SqlDataAdapter(sql, con);
ds = new DataSet();
dataAdapter.Fill(ds, "Impi");
impdg.DataSource = ds.Tables["Impi"].DefaultView;
crmng = (CurrencyManager)impdg.BindingContext[ds.Tables[0]];
tootip = new ToolTip();
con.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region Save the Records to the DataBase
private void btnSave_Click(object sender, EventArgs e)
{
try
{
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
// cb.DataAdapter.Update(ds.Tables["Impi"]);
DataRow dr = ds.Tables["Impi"].NewRow();
dr[0] = txtSerial.Text;
if (txtName.Text != "")
{
dr[1] = txtName.Text;
//Busy trying to solve exception errors and saving the record functionality without duplicating primary key
}
if (cbModel.Text == "MK1" || cbModel.Text == "MK2")
{
dr[2] = cbModel.Text;
}
if (cbStatus.Text == "Serviceble" || cbStatus.Text == "Unserviceble")
{
dr[3] = cbStatus.Text;
}
if (cbDeprtmnt.Text == "AIR" || cbDeprtmnt.Text == "LAND" || cbDeprtmnt.Text == "NAVY" || cbDeprtmnt.Text == "SPECIAL FORCE")
{
dr[4] = cbDeprtmnt.Text;
}
// ds.Tables["Impi"].Rows.Add(dr);
//This is where i stopped trying to figure out how to save my records properly
if (txtSerial.Text.Length!=0)
{
bool search = SearchSerialNumberBeforeSave(txtSerial.Text);
if (search == false)
{
DialogResult dr2 = MessageBox.Show("Are you sure you want to save this serial number", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr2 == DialogResult.Yes)
{
ds.Tables["Impi"].Rows.Add(dr);
dataAdapter.Update(ds, "Impi");
MessageBox.Show("Serial Number Added Successful");
}
// System.Data.SqlClient.SqlCommandBuilder cb;
//cb = new System.Data.SqlClient.SqlCommandBuilder(dataAdapter);
} //cb.DataAdapter.Update(ds.Tables["Impi"]);
else
{
MessageBox.Show("This Serial Number Exist and will create the duplicate.\nSerial Number not Saved");
MessageBox.Show("Data Entry was not saved", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please Enter a Impi Serial Number","Data Entry");
txtSerial.Text = "Please Enter Impi Serial Number";
txtSerial.ForeColor = Color.Red;
tootip.SetToolTip(txtSerial, txtSerial.Text);
}
// crmng.Position += 1;
// inc = crmng.Position - 1;
// btnAdd.Enabled = true;
// btnSave.Enabled = false;
if (txtName.Text.Length==0)
{
txtName.Text = "Please Enter the Track Number";
txtName.ForeColor = Color.Red;
tootip.SetToolTip(txtName, txtName.Text);
}
if (cbModel.Text.Length == 0)
{
cbModel.Text = "Please Select the Model Of the device";
cbModel.ForeColor = Color.Red;
tootip.SetToolTip(cbModel, cbModel.Text);
}
if (cbStatus.Text.Length == 0)
{
cbStatus.Text = "Please Select the status of the device";
cbStatus.ForeColor = Color.Red;
tootip.SetToolTip(cbStatus, cbStatus.Text);
}
if (cbDeprtmnt.Text.Length == 0)
{
cbDeprtmnt.Text = "Please Select the assigned department";
cbDeprtmnt.ForeColor = Color.Red;
}
else
{
MessageBox.Show("Data Entry was not Saved", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
#endregion
#region Search Method
public bool SearchSerialNumberBeforeSave(String name)
{
int result = 0;
DataRow[] retRows;
bool val;
//This line of code give this exception error Syntax error: Missing operand after 'No' operator.
retRows = ds.Tables["Impi"].Select("Serial No='" + name + "'");
result = retRows.Length;
if (result > 0)
{
val = true;
}
else
{
val = false;
}
return val;
}
#endregion
}
}
The space in Serial Nois causing this issue.
In order to solve it replace Serial No with [Serial No]
retRows = ds.Tables["Impi"].Select("[Serial No]='" + name + "'");
Take a look at this thread, It asks about the same issue.

StreamReader Multiple lines

I am trying to figure out how to read multiple lines whith StreamReader. I have a text file with a list of commands inside it that I need to read from. My code works, however it will only read the first line. This causes me to have to move all my commands to a single line with a space between them. This is not a very tidy way of doing this seeing as I need to leave comments next to the commands. Example: CONNECT: "Connects to given IP."
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}
This is what am using in one of my app and its working fine hope it'll help you out.......
if (TxtPath.Text != string.Empty)
{
StreamReader srr = new StreamReader(TxtPath.Text);
try
{
ss = srr.ReadToEnd().Split('\n');
MessageBox.Show("File Successfully Loded in Memory \n" + TxtPath.Text, "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
throw new Exception("File are not readable or write protacted");
}
LblLineCount.Text = ss.Count().ToString();
}
else
{
MessageBox.Show("Please Browse any Log File 1st", "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
you can also trim the
.Split('\n')
to take all data in single line, i can't try it right now but if check it will get u out of stuck...........
u should empty the variable after the loop, not inside the loop
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
}
else
{
COMBOX.Items.Add("Invalid Command");
}
}
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
string path = #"C:\\Users\\Home\\Desktop\\commands.txt";
WebClient client = new WebClient();
System.IO.Stream stream = client.OpenRead(path);
System.IO.StreamReader str = new StreamReader(stream);
string Text=str.ReadToEnd();
string[] words = Text.Split(':');
if (e.KeyCode == Keys.Enter)
{
for(int i=1;i<words.Length;i++)
{
if (string.compare(words[i],textBox1.text)==0)
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}
try this ..
use namespace using System.Net;

GUI Program crashes when trying to recall from a text file

I'm not sure what the problem is here. My program can read the "text" and put it in the Title without any problems, but it crashes and doesn't change the size or color before it does so. I tried asking my classmates for help regarding this, but they say all my code looks correct.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace RetrieveCustomizedForm
{
public partial class Form1 : Form
{
const char DELIM = ',';
string recordIn;
string[] fields;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
const string FILENAME = "C:\\Exercise5\\Data.txt";
stuff stuff1 = new stuff();
FileStream inFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
recordIn = reader.ReadLine();
reader.Close();
inFile.Close();
while (recordIn != null)
{
fields = recordIn.Split(DELIM);
stuff1.color = fields[0];
stuff1.size = fields[1];
stuff1.text = fields[2];
if (fields[0] == "red")
{
this.BackColor = System.Drawing.Color.Red;
}
if (fields[0] == "blue")
{
this.BackColor = System.Drawing.Color.Blue;
}
if (fields[0] == "yellow")
{
this.BackColor = System.Drawing.Color.Yellow;
}
if (fields[1] == "large")
{
this.Size = new System.Drawing.Size(500, 500);
}
if (fields[1] == "small")
{
this.Size = new System.Drawing.Size(300, 300);
}
this.Text = fields[2];
}
}
class stuff
{
public string color { get; set; }
public string size { get; set; }
public string text { get; set; }
}
}
}
fields : might be empty, end of the file?
Any file open error? trying to open it again while it is already opened in background?
Some more information might be helpful. Like The others have said, what are the values of fields[0]-[2]? What errors are you receiving? It looks to me like one error you will receive is that your index is outside the bounds of the fields array...Give us some more info and we can better help you.
try it this way
using (FileStream infile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(infile))
{
string recordIn = reader.ReadLine();
while (recordIn != null)
{
fields = recordIn.Split(DELIM);
stuff1.color = fields[0];
stuff1.size = fields[1];
stuff1.text = fields[2];
if (fields[0] == "red")
{
this.BackColor = System.Drawing.Color.Red;
}
if (fields[0] == "blue")
{
this.BackColor = System.Drawing.Color.Blue;
}
if (fields[0] == "yellow")
{
this.BackColor = System.Drawing.Color.Yellow;
}
if (fields[1] == "large")
{
this.Size = new System.Drawing.Size(500, 500);
}
if (fields[1] == "small")
{
this.Size = new System.Drawing.Size(300, 300);
}
this.Text = fields[2];
}
}
}

Categories

Resources