Note :This post is first published on Apr-2013 in my previous blog Techkindle. Moving the content here.
Steps:
- First, by using the File class static method ReadAllLines(path), read all the lines from the csv file to the string array.
- In the resulting array, first element contains the column names. using the first line, we should create the Data table columns.
- Other than the first element, all other elements contains the row’s data. Using the same we can create the data table rows.
using System; | |
using System.Text; | |
using System.Data; | |
using System.IO; | |
namespace ReadData | |
{ | |
class DataConvert | |
{ | |
static void Main(string[] args) | |
{ | |
CsvToDataTable obj = new CsvToDataTable(); | |
DataTable dtData = obj.ConvertCsvToDataTable(@"D:\student.csv"); | |
obj.ShowData(dtData); | |
} | |
class CsvToDataTable | |
{ | |
public DataTable ConvertCsvToDataTable(string filePath) | |
{ | |
//reading all the lines(rows) from the file. | |
string[] rows = File.ReadAllLines(filePath); | |
DataTable dtData = new DataTable(); | |
string[] rowValues = null; | |
DataRow dr = dtData.NewRow(); | |
//Creating columns | |
if (rows.Length > 0) | |
{ | |
foreach (string columnName in rows[0].Split(',')) | |
dtData.Columns.Add(columnName); | |
} | |
//Creating row for each line.(except the first line, which contain column names) | |
for (int row = 1; row < rows.Length; row++) | |
{ | |
rowValues = rows[row].Split(','); | |
dr = dtData.NewRow(); | |
dr.ItemArray = rowValues; | |
dtData.Rows.Add(dr); | |
} | |
return dtData; | |
} | |
public void ShowData(DataTable dtData) | |
{ | |
if (dtData != null && dtData.Rows.Count > 0) | |
{ | |
foreach (DataColumn dc in dtData.Columns) | |
{ | |
Console.Write(dc.ColumnName + " "); | |
} | |
Console.WriteLine("\n———————————————–"); | |
foreach (DataRow dr in dtData.Rows) | |
{ | |
foreach (var item in dr.ItemArray) | |
{ | |
Console.Write(item.ToString() + " "); | |
} | |
Console.Write("\n"); | |
} | |
Console.ReadKey(); | |
} | |
} | |
} | |
} | |
} |
Happy Learning 🙂