How to read data from CSV file
We need to save our data and read it from there through some code most of the time. It is not possible to read it from the console all the time. So exchanging text file format is the common way to transfer data from one program to another or to someone who might require that data for some purpose. CSV is one of the popular data formats for storing the data. Now why csv ? csv is Comma Separated Values and the benefit is you can store data just like a key-value pair and you can open that file in Excel. So storing the data is really very easy and easy to understand.
One thing is very clear here: we will not create a csv parser , we will use an existing parser available in the market. Here in this blog, I will use csvHelper for C#. .
Here I am going to use VSCode to implement the code. You can use same code for any C# editor.
Let's install csvHelper from Nuget .
Navigate to https://www.nuget.org .
Search for csvHelper or direct navigate to https://www.nuget.org/packages?q=csvHelper
dotnet add package CsvHelper --version 15.0.5
Here I am going to use the latest version of csvHeler.
Project Creating in VSCode
Open VSCode.
Goto view ->Tarminal
Write “dotnet new console” . This will create a sample project
Installing csvHelper from Terminal
Open Terminal
Write “dotnet add package CsvHelper --version 15.0.5
Now we can use “using CsvHelper”; in our code.
Before writing the code we need to create a csv file first. My csv file will look like this.
If I open it in Excel or calc, it will just like excel format .
Here my intention is user will provide the row name and column and code will return the cell value . Row name and column should be unique.
using System;
using CsvHelper;
using System.IO;
using System.Data;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
DataTable dataTable=null;
string rowname =Console.ReadLine();
string columnname=Console.ReadLine();
using (var reader = new StreamReader(@"C:\Users\anjan\Desktop\mycsv.csv"))
using (var csv = new CsvReader(reader, System.Globalization.CultureInfo.InvariantCulture))
{
using (var dr = new CsvDataReader(csv))
{
dataTable = new DataTable();
dataTable.Load(dr);
}
DataRow[] rows = dataTable.Select("ROWNAME='"+rowname+"'");
foreach(DataRow row in rows)
{
Console.WriteLine("value is ="+ row[columnname]);
}
}
}
}
}
Output
Time Elapsed 00:00:05.17
PS C:\Users\anjan\TestProject> dotnet run
ROW1
COLUMN3
value is =data3
PS C:\Users\anjan\TestProject>