How to import CSV files into DataTable in C#

Below is code the which you can use for converting a csv file into Data Table in C#. This method also handles comma values inside a double quoted value.
1. Provide the file path of your csv file:

string sCsvFilePath = @"C:\Downloads\Sample.csv";

2. Call Custom Method:

DataTable dtTable = ConvertCSVtoDataTable(sFilePath);

3. Copy and Paste below:

public static DataTable ConvertCSVtoDataTable(string sCsvFilePath)
    DataTable dtTable = new DataTable();
    Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
    using (StreamReader sr = new StreamReader(sCsvFilePath))
        string[] headers = sr.ReadLine().Split(',');
        foreach (string header in headers)
        while (!sr.EndOfStream)
            string[] rows = CSVParser.Split(sr.ReadLine());
            DataRow dr = dtTable.NewRow();
            for (int i = 0; i < headers.Length; i++)
                dr[i] = rows[i].Replace("\"",string.Empty);
    return dtTable;


  1. this is copied from below link.


Post a Comment

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

go to top image