-4

I am very new to C# and am trying to feel it out. Slow going so far! What I am trying to achieve should be relatively simple; I want to read a row from a CSV file with a search. I.e. if I search for username "Toby" it would fetch the entire row, preferably as an array.

Here is my users.csv file:

Id,Name,Password
1,flugs,password
2,toby,foo

I could post the code that I've tried, but I haven't even come close in previous attempts. It's a bit easier to do such a thing in Python, it may be easy in C# too but I'm far too new to know!

Does anyone have any ideas as to how I should approach/code this? Many thanks.

  • [FileHelpers](https://github.com/MarcosMeli/FileHelpers) • [CsvHelper](https://github.com/JoshClose/CsvHelper) • [FlatFiles](https://github.com/jehugaleahsa/FlatFiles) • [NugetMustHaves:CSV](https://nugetmusthaves.com/Package?q=csv) –  Aug 21 '21 at 16:51
  • Does this answer your question? [Reading CSV files using C#](https://stackoverflow.com/questions/3507498/reading-csv-files-using-c-sharp) and [Parsing CSV files in C#, with header](https://stackoverflow.com/questions/2081418/parsing-csv-files-in-c-with-header) and [Importing CSV data into C# classes](https://stackoverflow.com/questions/7702573/importing-csv-data-into-c-sharp-classes) and [Reading CSV file and storing values into an array](https://stackoverflow.com/questions/5282999/reading-csv-file-and-storing-values-into-an-array) –  Aug 21 '21 at 16:51
  • It helps, thank you, but I simply do not understand how to capture the entire row by searching one value. – flugscoding Aug 21 '21 at 17:05
  • Read each line; test if it satisfies your search terms; if not, discard it and read the next one; if so, process the record. – Mark Benningfield Aug 21 '21 at 17:39

1 Answers1

3

Easy to do in c# too:

var lineAsArray = File.ReadLines("path").First(s => s.Contains(",toby,")).Split(',');

If you want case insens, use e.g. Contains(",toby,", StringComparison.OrdinalIgnoreCase)

If your user is going to type in "Toby" you can either concatenate a comma on the start/end of it to follow this simplistic searching (which will find Toby anywhere on the line) or you can split the lone first and look to see if the second element is Toby

var lineAsArray = File.ReadLines("path").Split(',').First(a => a[1].Equals("toby"));

To make this one case insensitive, put a suitable StringComparison argument into the Equals using the same approach as above


Sky's the limit with how involved you want to get with it; using a library that parses CSV to objects that represent your lines with named, typed parameters is probably where I'd stop.. take a look at CSVHelper from josh close or ServiceStack Text, though there are no shortage of csv parser libs- it's been done to death!

Caius Jard
  • 72,509
  • 5
  • 49
  • 80