First things first, you need to get to know your CSV file, how many columns does it have and so on...
For each column you may need a list for contain the data or not, let's take a two-column CSV file
Name | Comment |
---|
The data in the CSV must have this structure
Name;Comment
The data below the columns' name will correspond to every header present in the file.
Let's see an example of a pretty CSV file
Name;Comment
John Doe;Example
The first line correspond to the headers, next lines contains data itself.
Now, let's dive into the C# app.
For every header, you need a list to collect all the data and you need to specify
the CSV's path
List<string> nameColumn = new List<string>();
List<string> commentColumn = new List<string>();
string pathCSV = @"C:\example\paht\file.csv";
Next, we need to create and use a StreamReader
object to read data from the CSV
using (var reader = new StreamReader(pathCSV))
{
// Add logic here
reader.Close();
}
As a little example, we can do something like this:
List<string> usernames = new List<string>();
List<string> comments = new List<string>();
var pathCSV = @"";
using (var reader = new StreamReader(pathCSV))
{
while (!reader.EndOfStream)
{
// Example made with two-column CSV
string line = reader.ReadLine()!;
var values = line.Split(';');
// Add more lists and columns as you need
usernames.Add(values[0]);
comments.Add(values[1]);
}
reader.Close();
}
print(usernames);
Console.WriteLine("----------------------");
print(comments);
Console.ReadLine();
void print(List<string> list)
{
foreach (var item in list)
{
Console.WriteLine(item);
}
}