I am working in c-sharp .net and I am working on creating a login screen for my project. I have a text file with login info for all the users. My c-sharp scrip reads that file to a string then cuts it up into two lists, _usernames and _passwords. When the user types their login info and hits login the _usernames[0] and _passwords[0] account info are the only ones that work. What I want it to do is look through all the _usernames for the inputted one, if it finds it then check the _password[same index as _usernames] and if both are the same as what the user submitted then it will add "true" to the richTextBox.
Why is it not correctly reading from the array?
This is my users.txt:
admin,test|
andrew,yeet|
zana,happy|
This is my c-sharp script:
using System;
using System.IO;
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;
namespace BaseUserInterfase
{
public partial class Login : Form
{
string path = Directory.GetCurrentDirectory() + "\\data\\users.txt";
string data;
string[] _usernames = new string[10];
string[] _passwords = new string[10];
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
GetLoginData();
}
private void btnLogin_Click(object sender, EventArgs e)
{
rtbTemp.Text = "";
for(int i = 0; i < _usernames.Length; i++)
{
if(_usernames[i] == null)
{
break;
}
rtbTemp.AppendText("\n" + _usernames[i]);
rtbTemp.AppendText("\n" + tbUsername.Text.ToString());
rtbTemp.AppendText("\n" + _passwords[i]);
rtbTemp.AppendText("\n" + tbPassword.Text.ToString());
if (_usernames[i] == tbUsername.Text.ToString())
{
rtbTemp.AppendText("\nUsername true");
if (_passwords[i] == tbPassword.Text.ToString())
{
rtbTemp.AppendText("\nPassword true");
rtbTemp.AppendText("\ntrue");
return;
}
}
}
rtbTemp.AppendText("\nfalse");
}
public void GetLoginData()
{
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
data = streamReader.ReadToEnd();
}
List<string> _data = data.Split('|').ToList();
_data.RemoveAt(_data.Count - 1);
rtbTemp.AppendText("\n");
Array.Resize<string>(ref _usernames, _data.Count);
Array.Resize<string>(ref _passwords, _data.Count);
foreach (string _item in _data)
{
List<string> userdata = _item.Split(',').ToList();
string username = userdata[0].ToString();
string password = userdata[1].ToString();
Console.WriteLine(_item);
Console.WriteLine(username);
Console.WriteLine(password);
for(int i = 0; i < _data.Count; i++)
{
if(_usernames[i] == null)
{
_usernames[i] = username;
_passwords[i] = password;
break;
}
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
And this is an image of the login screen:
1
Your file contains carriage return characters. Remove them before you split its content
data = streamReader.ReadToEnd().Replace("\r\n", "");
Related
I am currently working on a windows forms app using c# that will be able to convert Pastel Partner trial balances to Pastel Evolution compatible balances.
I am trying to implement code that will skip all lines in the sheet that do not have account codes (col 2)
Please assist with a code example on how to do this, it would be highly appreciated!
The excel sheet needs to convert from this (Partner)...
To this (Evolution)...
This is my form and code so far...
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;
namespace Evo_Mod
{
public partial class Form1 : Form
{
public string date; // set by user
public string codeDate; // set by date and OB string
public string OB = "OB"; // set value
public string zero = "0"; // set value
public string accCode; // needs to be read from the first excell sheet and printed with a ">"
public string contraCode = "9990>001"; // set value
public bool credCheck = false; // bool that is interactive
public bool debCheck = false; // bool that is interactive depending on whether the account is in credit or debit
public string fileName = ""; // set from the openFileDialog
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) // lets user select csv file.
{
openFileDialog1.ShowDialog();
openFileDialog1.Filter = "CSV Files (L*.csv)|L*.csv"; // Filters to only .csv files
fileName = openFileDialog1.FileName;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
lblFileName.Text = openFileDialog1.FileName; // prints file directory
}
}
public static string[] ReadCSV(string searchTerm , string filePath , int positionOfSearch)
{
positionOfSearch--; // moves over by 1 (more understandable)
string[] recordNotFound = { " Record Not Found " }; // array for errors
try
{
string[] lines = System.IO.File.ReadAllLines(#filePath);
for (int i = 0; i < lines.Length; i++)
{
string[] fields = lines[i].Split(',');
if (recordMatches(searchTerm , fields , positionOfSearch))
{
return fields;
}
}
return recordNotFound;
}
catch(Exception ex)
{
Console.WriteLine("error");
return recordNotFound;
throw new ApplicationException("Error : ", ex);
}
}
public static bool recordMatches(string searchTerm , string[] record , int positionOfSearch)
{
if (record[positionOfSearch] != " ")
{
return true;
}
return false;
}
private void btnConvert_Click(object sender, EventArgs e)
{
DateTime tempDate = dateTimePicker1.Value;
codeDate = "OB " + tempDate.ToString("dd/MM/yyyy");
date = tempDate.ToString("dd/MM/yyyy");
}
}
}
If the account codes are in col 2, then you can check for empty values in the loop which you already have
string[] fields = lines[i].Split(',');
if (fields[1] != "") <-- check if account code is an empty string
{
if (recordMatches(searchTerm , fields , positionOfSearch))
{
...
Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.
I am a C # amateur I am not a professional developer and would like to ask my colleagues for help, I would like to make a C # program that connects to an SSH server. Then, depending on the selected value in combobox, the program downloads the appropriate string and I would like to send it to the ssh server to the specified path path and save the value from the string to the file;)
I tried to rewrite the code but something did not work out and I stopped in my place ;( Can anyone help me. Thanks in advance for your help.
this 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.Threading;
using Renci.SshNet;
namespace FileGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SshClient sshClient = new SshClient("192.168.1.22", 22, "root", "pass");
sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
sshClient.Connect();
ShellStream shellStreamSSH = sshClient.CreateShellStream("vt-100", 80, 60, 800, 600, 65536);
Thread thread = new Thread(() => recvSSHData(shellStreamSSH));
thread.Start();
//I don't know how to get the information if it is connected correctly and change e.g. btnConnect label to Connected.
}
public static void recvSSHData(ShellStream shellStreamSSH)
{
while (true)
{
try
{
if (shellStreamSSH != null && shellStreamSSH.DataAvailable)
{
string strData = shellStreamSSH.Read();
}
}
catch
{
}
System.Threading.Thread.Sleep(200);
}
}
string data1 = "data1";
string data2 = "data2";
string data3 = "data3";
string check;
string path = "/home/test01/desktop";
string filename = "test.txt";
private void btnSend_Click(object sender, EventArgs e)
{
if (cmbData.SelectedIndex == 0)
{
check = data1;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 1)
{
check = data2;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 2)
{
check = data3;
MessageBox.Show(check);
}
else
{
MessageBox.Show("Choose a value");
}
//And now there should be an instruction that sends a string check to the server to path to file replacing its contents
}
}
}
Ok, I coped with everything but I am on the last step, how to save the contents of string to a file using client scp ??
string text= "bal bla bla bla bla"
string path = "#/home/test01/desktop/";
string filename = "test1.txt"
...
try
{
MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(text));
scpClient.Upload(mStrm, path + filename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have error:
Renci.SshNet.Common.ScpException: scp: error: unexpected filename:
w Renci.SshNet.ScpClient.CheckReturnCode(Stream input)
w Renci.SshNet.ScpClient.UploadFileModeAndName(IChannelSession channel, Stream input, Int64 fileSize, String serverFileName)
w Renci.SshNet.ScpClient.Upload(Stream source, String path)
w FileGenerator.Form1.btnSend_Click(Object sender, EventArgs e) w C:\Users\backu\source\repos\FileGenerator\FileGenerator\Form1.cs:wiersz 192
I need to return all the peaks and valleys from the data in the csv file. I keep getting an exception when I run the program telling me the string isn't in correct format. I don't know what I'm writing incorrectly. I'm passing the values into testX and testY and then comparing them in my while loop. The while loop is where I'm getting the error when I convert testY to a double.
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 WindowsFormsApp6
{
public partial class Form1 : Form
{
double firstY = 0.0;
string testX;
string testY;
string[] xpoint = new string[5000];
string[] ypoint = new string[5000];
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (var reader = new StreamReader(#"D:\data.csv"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
var values = line.Split(',');
testX = values[0];
testY = values[1];
while (Convert.ToDouble(testY) <= firstY)
{
firstY = Convert.ToDouble(testY);
if (firstY == Convert.ToDouble(testY))
{
break;
}
}
if (Convert.ToDouble(testY) > firstY)
{
listBox1.Items.Add(Convert.ToDouble(testX) + "," + firstY);
}
while (Convert.ToDouble(testY) >= firstY)
{
firstY = Convert.ToDouble(testY);
if (firstY == Convert.ToDouble(testY))
{
break;
}
}
if (Convert.ToDouble(testY) < firstY)
{
listBox2.Items.Add(Convert.ToDouble(testX) + "," + firstY);
}
Convert.ToString(testX);
Convert.ToString(testY);
}
}
}
}
}
i am currently working on a Windows Forms App in c# which will allow the user to add or delete records. when i hit the button to display all the records written to the file the files appear, but when i try to delete by transact number i get an exception saying that "The process cannot access the the because it is being used somewhere else". i have tried putting it in a try-catch block to make sure the reader/writer will close and still not working code will be attached any help is greatly appreciated. p.s im not looking for code to finish this project just help getting by this exception and make it work like it is suppose.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MMFileIO
{
public partial class MMAssignment3 : Form
{
StreamWriter writer;
StreamReader reader;
string record = "";
public MMAssignment3()
{
InitializeComponent();
}
private void MMAssignment3_Load(object sender, EventArgs e)
{
txtFile.Text = #"c:\burnable\assignment3.txt";
if (!Directory.Exists(txtFile.Text.Substring
(0, txtFile.Text.LastIndexOf('\\'))))
MessageBox.Show("File path does not exist");
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (radNew.Checked)
writer = new StreamWriter(txtFile.Text, append: false);
else
writer = new StreamWriter(txtFile.Text, append: true);
}
catch(Exception ex)
{
if (writer != null)
writer.Close();
MessageBox.Show($"exception adding new record: {ex.Message}");
return;
}
record = $"{txtTransact.Text}::{txtDate.Text}::{txtSerial.Text}::" +
$"{txtToolPurchased.Text}::${txtPrice.Text}::{txtQty.Text}::" +
$"${txtAmount.Text}";
try
{
writer.WriteLine(record);
lblMessage.Text = ($"Record added");
txtTransact.Text = txtDate.Text = txtSerial.Text =
txtToolPurchased.Text = txtPrice.Text = txtQty.Text =
txtAmount.Text = "";
}
catch(Exception ex)
{
MessageBox.Show($"exception adding a new record: {ex.Message}");
}
finally
{
writer.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
List<string> records = new List<string>();
while (! reader.EndOfStream)
{
record = reader.ReadLine();
records.Add(record);
}
if (records.Count == 0)
MessageBox.Show("No records left in file");
reader.Close();
writer = new StreamWriter(txtFile.Text, append: false);
foreach (string item in records)
{
}
}
private void btnCloseFile_Click(object sender, EventArgs e)
{
txtDataDisplay.Text = "";
reader.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
txtDataDisplay.Text = $"{"#".PadRight(10)}\t" +
$"{"Purchase-Date".PadRight(10)}\t{"Serial #".PadRight(10)}\t" +
$"{"Manufacturing Tools".PadRight(10)}\t{"Price".PadRight(10)}\t" +
$"{"Qty".PadRight(10)}\t{"Amount".PadRight(10)}\n{"".PadRight(50)}\n";
while (!reader.EndOfStream)
{
record = reader.ReadLine();
string[] fields = record.Split(new string[] { "::" }, StringSplitOptions.None);
txtDataDisplay.Text += $"{fields[0].PadRight(10)}\t" +
$"{fields[1].PadRight(10)}\t{fields[2].PadRight(10)}\t" +
$"{fields[3].PadRight(30)}\t{fields[4].PadRight(10)}\t" +
$"{fields[5].PadRight(10)}\t{fields[6].PadRight(10)}\n";
}
reader.Close();
}