program shifts data to the right by 1 - c#

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.

Related

Processing data in datagridview became very slow

So I have this program I made a couple of years ago that helps me process and correct data I have for my work. I run it once an year and forget about it till the next year.
I have a big data file (usually over 800k+ rows and 5 columns) that have to go through various checks for data correctness. I bind the file via an excel spreadsheet into the datagridview like this:
public DataTable ReadExcel(string fileName, string fileExt)
{
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
{
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO';"; //for above excel 2007
}
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch { }
}
return dtexcel;
}
Also I load the file using this:
private void loadExcelTable_Click(object sender, EventArgs e)
{
string filePath = string.Empty;
string fileExt = string.Empty;
OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file
if (file.ShowDialog() == DialogResult.OK) //if there is a file choosen by the user
{
filePath = file.FileName; //get the path of the file
fileExt = System.IO.Path.GetExtension(filePath); //get the file extension
textBox1.Text = filePath; //display the path to the file in the loadFile text box
if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
{
try
{
this.Cursor = Cursors.WaitCursor;
phoneGridView1.VirtualMode = true;
phoneGridView1.Visible = true;
phoneGridView1.DataSource = ReadExcel(filePath, fileExt);
this.Cursor = Cursors.Default;
MessageBox.Show("Файлът зареден успешно!", "Success!", MessageBoxButtons.OK); //custom message for successful file loading
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
else
{
MessageBox.Show("Моля изберете .xlsx файл.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error
}
}
}
After everything is loaded, I press the button and various checks on the data start happening internally (lots of ifs involved).
Last year when I did this, everything went smoothly and the checks went out for about 3h on the whole file. THIS YEAR something changed. I dont know if it is from some VS2019 update or something, but the internal checks were taking way way way more time. I let the file sit for a whole week and it didnt even check half of it.
My questions are: is there a way to get things working as before? Did some update during that year changed the way the datagridview processes data?
I didnt do any changes to the code between my last working and now. The only thing that was changed was that I changed my GPU, but I dont believe this can cause such a huge drop in performance (I upgraded, no downgraded).
Any kind of help with this issue will be much appreciated.
Sample code of internal checks for data validation:
private void checkEmail(string email, int i)
{
//counts the symbols after the # symbol
string afterSymbol = email.Substring(email.LastIndexOf('#') + 1);
int lenght = afterSymbol.Length;
if (email.Contains("#") && email.Contains(".") && lenght >= 5)
{
phoneGridView1.Rows[i].Cells[4].Value = "01";
}
else
{
phoneGridView1.Rows[i].Cells[4].Value = "02";
}
phoneGridView1.Update();
}
Button_click function: All functions that are called here consists of various segments like the code segment above that checks the data in the datagridview
private void checks_Click(object sender, EventArgs e)
{
if (phoneGridView1.Rows.Count != 0)
{
int maxRows = phoneGridView1.RowCount;
int maxColumns = phoneGridView1.ColumnCount;
string fieldValue;
DataTable Codes1 = Codes(textBox2.Text);
Codes1.PrimaryKey = new DataColumn[] { Codes1.Columns["Column1"] };
this.Cursor = Cursors.WaitCursor;
if (Codes1.Rows.Count >0)
{
//Check each row if it contains one of the appointed values
for (int i = 1; i < maxRows; i++)
{
fieldValue = phoneGridView1.Rows[i].Cells[3].Value.ToString();
//Checks if the value in the row is the email
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "3")
{
checkEmail(fieldValue, i);
}
//Checks if the value in the row is GSM number
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "5")
{
checkGSM(fieldValue, i);
}
//Check if the telephone number is correct
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "1")
{
checkTelephone(fieldValue, i, Codes1);
}
//Check if the fax number is correct
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "2")
{
checkFax(fieldValue, i, Codes1);
}
//Check if the web page is correct
if (phoneGridView1.Rows[i].Cells[2].Value.ToString() == "6")
{
checkWeb(fieldValue, i);
}
if (phoneGridView1.Rows[i].Cells[4].Value.ToString() == string.Empty)
{
phoneGridView1.Rows[i].Cells[4].Value = "19";
}
}
this.Cursor = Cursors.Default;
MessageBox.Show("Успешно проверени данни!", "Success!", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("Моля въведете файл със кодовете на населените места!", "Error!", MessageBoxButtons.OK);
}
}
else
{
MessageBox.Show("Моля въведете файл за проверка!", "Error!", MessageBoxButtons.OK);
}
}

Wrong username and password 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);
}
*/
}
}

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.

Reading from a text file using C#

So I'm making a chat program but I am having issues creating a new line in the text box instead of overwriting the other message. Here is my code:
private void refreshRate_Tick(object sender, EventArgs e)
{
String ChatPath = #"Path";
String line;
try
{
StreamReader sr = new StreamReader(#"Path");
line = sr.ReadLine();
richTextBox1.Text = null;
while (line != null)
{
richTextBox1.AppendText(Environment.NewLine);
richTextBox1.Text = line;
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception r)
{
Console.WriteLine("Exception: " + r.Message);
}
finally
{
}
}
You don't need StreamReader or Environment.NewLine
richTextBox1.Text=File.ReadAllText(path);
I think you want to remove the line
richTextBox1.Text = line;
and add
richTextBox1.AppendText(line);
after you've read it from the file.
If you change
richTextBox1.Text = line to richTextBox1.AppendText(line); you'll lose the last line so change the while block as:
while (line != null)
{
richTextBox1.AppendText(Environment.NewLine);
line = sr.ReadLine();
richTextBox1.AppendText(line??"");
}

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;

Categories

Resources