Ramco Ramco

Ramco Ramco

  • 442
  • 3.4k
  • 528.4k

How to uplad csv file and save data in DataTable

Apr 13 2023 8:58 AM

Hi

  I have .csv file and want to upload its data in datatable. I am trying below code but it is giving Invalid File Signature

public static DataTable ReadCSVFile(string fileName)
{
    using (var stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
    {
        // Auto-detect format, supports:
        //  - Binary Excel files (2.0-2003 format; *.xls)
        //  - OpenXml Excel files (2007 format; *.xlsx, *.xlsb)
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            do
            {
                while (reader.Read())
                {
                    // reader.GetDouble(0);
                }
            } while (reader.NextResult());


            DataSet result = reader.AsDataSet();
            return result.Tables[0];
        }
    }
}

Thanks


Answers (8)