Below is code the which you can use for converting a csv file into Data Table in C#. This method also handles comma values inside a double quoted value.
1. Provide the file path of your csv file:
string sCsvFilePath = @"C:\Downloads\Sample.csv";
2. Call Custom Method:
DataTable dtTable = ConvertCSVtoDataTable(sFilePath);
3. Copy and Paste below:
public static DataTable ConvertCSVtoDataTable(string sCsvFilePath)
{
DataTable dtTable = new DataTable();
Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
using (StreamReader sr = new StreamReader(sCsvFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dtTable.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = CSVParser.Split(sr.ReadLine());
DataRow dr = dtTable.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i].Replace("\"",string.Empty);
}
dtTable.Rows.Add(dr);
}
}
return dtTable;
}
this is copied from below link.
ReplyDeletehttps://immortalcoder.blogspot.com/2013/12/convert-csv-file-to-datatable-in-c.html
The King Casino Online ᐈ Get 50% up to €/$100 + 50 Free Spins
ReplyDeleteGet 50% up to https://jancasino.com/review/merit-casino/ €/$100 + 50 Free Spins · Visit the หารายได้เสริม official site · Log in to your Casino jancasino.com Account · If you do not agree https://febcasino.com/review/merit-casino/ to the septcasino.com terms of the terms of the agreement,