How to read data from CSV file using c#.net and asp.net?

How to read data from CSV file using c#.net and asp.net?

In this article, I am going to write the code to read data from CSV file into .NET DataTable by using TextFieldParser and then display in a GridView by using asp.net and c#.net. TextFieldParser class is not available in C# library. It is available in VisualBasic class. So we need to add the reference to Microsoft.VisualBasic.

Follow below steps :

Step 1 : Open Visual Studio
Step 2 : Create New Website with c# as code behind
Step 3 : Then rename the website as ReadCSVFile.
Step 4 : Right-click on the website name in Solution Explorer and click on Add and then click on Reference
ReadCSVFileReferenceAdd

Step 5 : Select Microsoft.VisualBasic from the list and click OK button

addReference2

You can use the following code to read data from CSV file in C#.Net:

using System;
using System.Data;
using Microsoft.VisualBasic.FileIO;

// Summary description for ReadCSVData
public class ReadCSVData
{
    public ReadCSVData()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public static DataTable GetDataTabletFromCSVFile(string csvFilePath)
    {
        DataTable csvData = new DataTable();
        try
        {
            using (TextFieldParser csvReader = new TextFieldParser(csvFilePath, System.Text.Encoding.UTF8))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;
                //read column names
                string[] colFields = csvReader.ReadFields();
                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }
                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();
                    //Making empty value as null
                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
        }
        catch (Exception ex)
        {
        }
        return csvData;
    }

}

Download Full Source Code from Below link :
ReadCSVFile.zip