How to Convert CSV file to C# Data Table

This code will help you to import a CSV file into DataTable using C#. As you know that a CSV file is like a text file which contains data fields separated by delimiter (comma, semicolon, pipe etc.).

So this must be known to you that which character is used to separate the values. In the blow given code snippet you need to define the CSV delimiter character of CSV file.

Step 1: Use this namespace at the starting of your code.

using System.IO;

Step2: Declare the variable to hold the path of CSV file and delimiter of CSV file.

string CsvFilePath = @"C:\TEST\Sample_CSV.csv";
char csvDelimiter = ';';

Step3: Define the function as below.

public DataTable CSVtoDataTable(string strFilePath, char csvDelimiter)
        {
            DataTable dt = new DataTable();            
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(csvDelimiter);
                foreach (string header in headers)
                {
                    try
                    {
                        dt.Columns.Add(header);
                    }
                    catch { }
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(csvDelimiter);
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }
            return dt;
        }

Step4: Call the function as shown below at suitable place in your code.

DataTable dt = CSVtoDataTable(CsvFilePath, csvDelimiter);

Leave a Reply