Converting CSV to DataTable in C#
In C#, the DataTable
class from the System.Data
namespace provides a easy way to represent tabular data. To convert a CSV file into a DataTable
, you need to parse the file, extract the data, and populate the DataTable
accordingly.
using System;
using System.Data;
using System.IO;
class Program
{
static void Main()
{
DataTable dataTable = new DataTable();
using (StreamReader reader = new StreamReader("sample_data.csv"))
{
string[] headers = reader.ReadLine().Split(',');
foreach (string header in headers)
{
dataTable.Columns.Add(header);
}
while (!reader.EndOfStream)
{
string[] rows = reader.ReadLine().Split(',');
DataRow dataRow = dataTable.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dataRow[i] = rows[i];
}
dataTable.Rows.Add(dataRow);
}
}
// Output the DataTable
foreach (DataRow row in dataTable.Rows)
{
foreach (var item in row.ItemArray)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
}
}
Output:
Name Age Gender
Peter 32 Male
Rose 28 Female
Ram 21 Male
Dan 30 Male
Kat 35 Female
Comments (0)