C# Console Application

How to Read CSV File in C#

In this tutorial you will learn How to Read CSV File in C# Console. Firstly we must create for read a CSV file. The following LoadCSV method reads the CSV file into a two – dimensional array of strings.

 




The code uses System.IO.File.ReadAllText to read the file’s contents into a string. It then uses Split to break the file into lines, ignoring any blank lines.

The code then loops through the lines using Split to split the lines into fields and adding their values to the array. When it’s done, the method returns the two-dimensional array of strings.

When Main method load, the following code calls the LoadCSV method and displays the result on Console Screen.

I used this sample file

 

Solution 1: Write all data into Console

This code calls LoadCSV and saves the returned strings in an array. It uses the array’s GetUpperBound method twice to see how many rows and columns it contains.

Next the program loops through the first values in each of the array’s columns and uses it to build a column in Console. For each value, it creates a column named after the value and displaying the value as its header text.

Next the code loops through the remaining rows in the table. For each row, it adds the row’s values into Console.

 

Solution 2: Create custom object for each elements from CVS and Fill a LIST with custom objects

Create Person class as following:

Creating Main method and LoadCSV codes:

Output:

 

 

 

About the author

admin

Leave a Comment