Sandeep Kumar

Sandeep Kumar

  • 1.1k
  • 683
  • 59.4k

Error Showing when Imporing Data from CSV file to datatable

May 5 2023 6:03 AM

Error Msg="A column named '1' already belongs to this DataTable."

this is my CSV file which i want to import and make datatable

My Code is 

public static DataTable ConvertCSVtoDataTable(dynamic file)
{
    DataTable dt = new DataTable();
    using (StreamReader sr = new StreamReader(file.InputStream))
    {
        string[] headers = sr.ReadLine().Split(',');
        foreach (string header in headers)
        {
            dt.Columns.Add(header);
        }
        while (!sr.EndOfStream)
        {
            string[] rows = sr.ReadLine().Split(',');
            DataRow dr = dt.NewRow();
            for (int i = 0; i < headers.Length; i++)
            {
                dr[i] = rows[i];
            }
            dt.Rows.Add(dr);
        }
    }
    return dt;
}


Answers (1)