简体   繁体   中英

C#: How to check user console input against a column in a .csv?

Yo,

I am fairly new to C# and I'm making a small text based console RPG game just for practice and I was wondering if there was anyway I could make something similar to this:

  • Ask user for name
  • Ask user for password
  • Check if the name is in column 1 of a .csv file
  • If it is, check if the password is in column 2 and in the same row as the name
  • If everything checks out, load the values from columns 3 and 4 in the same row as the name and password into corresponding values like health and level

Here's an example .csv if I didn't really explain it well:

"charactername", "password123", "health", "level"
"Oswald", "498562a", "100", "4"
"Hammerfist", "98457813", "77", "6"

So just for the sake of clarity, this is what I'm thinking:

  • Enter your username: Oswald
  • Enter your password: 498562a
    • Program reads through column 1 of the file looking for "Oswald" and finds a match
    • Program then checks to see if the password value is in the same row but in column 2 of the file and checks to see if it matches the user input, it matches it
    • Program then loads the health and level values into character variables
  • Entrance Successful

Is there a way to do this? Am I overlooking a simple solution? Or should I try and go about it a different way? I'm just don't want to hard code the values into a Dictionary or List or Array or whatever. I'm not looking for security at this stage either, it's just for practice and fun.

Thanks in advance! Let me know if you need a better understanding of what I'm trying to do and I'll try to explain the best I can.

There are two ways to go about reading csv

  1. Just like standard text file, line by line. Then parse your line into array of columns and get your values

  2. Using Microsoft.ACE.OLEDB.version

    OleDbconnection connection = new OleDbConnection(); connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Documents\\file.csv;Extended Properties=\\"Text;HDR=Yes;FORMAT=Delimited\\"";

This way you can load DataTable on the start of your app and query this table just like Sql database.

notice : HDR=Yes means that first row is a header row

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM