I am trying to read a *.csv
-file.
The *.csv
-file consist of two columns separated by semicolon (\";\").
I am able
You can't create an array immediately because you need to know the number of rows from the beginning (and this would require to read the csv file twice)
You can store values in two List
and then use them or convert into an array using List
Very simple example:
var column1 = new List();
var column2 = new List();
using (var rd = new StreamReader("filename.csv"))
{
while (!rd.EndOfStream)
{
var splits = rd.ReadLine().Split(';');
column1.Add(splits[0]);
column2.Add(splits[1]);
}
}
// print column1
Console.WriteLine("Column 1:");
foreach (var element in column1)
Console.WriteLine(element);
// print column2
Console.WriteLine("Column 2:");
foreach (var element in column2)
Console.WriteLine(element);
N.B.
Please note that this is just a very simple example. Using string.Split
does not account for cases where some records contain the separator ;
inside it.
For a safer approach, consider using some csv specific libraries like CsvHelper on nuget.