1

With a csv file looking like this:

usernames,passwords
us1,ps1
us2,ps2

I would like all usernames in one array an all passwords in another.

Current code: (Trying to make a login system that interacts with a database.)

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.Diagnostics;
using System.Globalization;

namespace Login
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string[] usernames = new string[] { };

        string[] passwords = new string[] { };

        private void btnLogin_Click(object sender, EventArgs e)
        {
            lblLoginSucsess.Text = "";

            for (int i = 0; i < Math.Min(usernames.Length, passwords.Length); i++)
            {
                if ((usernames[i].ToLower() == txtUsnme.Text.ToLower()) && (passwords[i].ToLower() == txtPass.Text.ToLower()))
                {
                    lblLoginSucsess.Text = $"Welcome, {txtUsnme.Text}.";
                    // run calc
                    Process.Start("C:/Users/finch/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/HP Inc/Calculator.appref-ms");
                }
            }
        }
    }
}

If you can help, Thanks.

Fin HARRIS
  • 118
  • 10
  • What have you tried so far and where did you struggle? – Mighty Badaboom Feb 27 '20 at 13:12
  • I know how to do it in python just new to c# and dont know where to start. – Fin HARRIS Feb 27 '20 at 13:17
  • From Exar666Kun : *please add code you have done so far, so we can check for any mistakes or give hints in other forms. to read lines of text, check System.IO.File.ReadAllLines to grab all lines of a file. the rest is up to you.* – Panagiotis Kanavos Feb 27 '20 at 13:19
  • 1
    Does this answer your question? [Reading CSV file and storing values into an array](https://stackoverflow.com/questions/5282999/reading-csv-file-and-storing-values-into-an-array) – Mohamad Mousheimish Feb 27 '20 at 13:23

1 Answers1

3

Instead of having two separate list, it would be better if you had a Dictionary of UserName/Password. You could read CSV and convert to dictionary by

var dataLines = File.ReadAllLines(filePath);
var userPassDictionary = dataLines.Skip(1)
                                  .Select(x=> x.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries))
                                  .ToDictionary(x=> x.First().ToLower(),v=>v.Last());

Now you could access validate the user as

if (userPassDictionary[txtUsnme.Text.ToLower()] == txtPass.Text)
{

}

Note

It was also curious to note that your were comparing password case-insensitevely. While it might depend on the business requirement, most often than not, passwords are case-sensitive. Wanted to highlight it, just in case, it was by accident.

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51