Home  »  Code Snippets  »  C#.Net  »

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

 Posted By : Manoranjan SahooPosted Date : 09/10/2014 05:42:44 PM Category : C#.Net Points : 15 (Rs 1.00)

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


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


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 :




For More Details Visit : http://lovelycodes.dotnetsquare.com/read-data-csv-file-using-c-net-asp-net/
Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.