Read CSV files in C#

Big Al Ruby Newbie picture Big Al Ruby Newbie · Jan 17, 2017 · Viewed 9.5k times · Source

I have the following code that imports excel documents and parses them so I can manipulate the data before it is saved to the database.

I can parse .xlsx and .xls files just fine but cannot figure out how to use my existing code for .csv files

the customer I am working for wants to use .csv file type to accept special characters.

OpenFileDialog opener = new OpenFileDialog();
opener.Filter = "Excel Files| *.xlsx;*.xls;*.csv;";
if (opener.ShowDialog() == DialogResult.Cancel)
    return;

FileStream streamer = new FileStream(opener.FileName, FileMode.Open);
IExcelDataReader reader;
if (Path.GetExtension(opener.FileName) == ".xls")
{
    reader = ExcelReaderFactory.CreateBinaryReader(streamer);
}
else if (Path.GetExtension(opener.FileName) == ".csv")
{

    *** Need Something Here to read CSV Files that will work with 
        the rest of code***
}
else
{
    reader = ExcelReaderFactory.CreateOpenXmlReader(streamer);
}
DataSet results = reader.AsDataSet();
results.Tables[0].Rows[0].Delete();
results.AcceptChanges();


foreach (System.Data.DataTable table in results.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
       >>> Do Something With the Data
    }
}

Answer

onur picture onur · Jan 17, 2017
private void ReadCSVFile(string filepath)
{
    //receiverList = new List<ReceiverUser>();

    try
    {
        if (filepath == string.Empty)
            return;

        using (StreamReader sr = new StreamReader(FileUpload1.PostedFile.InputStream))
        {
            string line;

            while ((line = sr.ReadLine()) != null)
            {
                SplitLine(line);
            }
        }

        #region row add test
        DataTable dt = new DataTable();

        if (dt.Columns.Count == 0)
        {
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Mail", typeof(string));
            dt.Columns.Add("Amount", typeof(double));
        }

        DataRow NewRow;
/*
        foreach (var item in receiverList)
        {
            NewRow = dt.NewRow();
            NewRow[0] = item.Name + " " + item.Surname;
            NewRow[1] = item.Mail;
            NewRow[2] = item.Amount;
            dt.Rows.Add(NewRow);
        }
*/


        grdRec.DataSource = dt;
        grdRec.DataBind();

        #endregion
    }
    catch (Exception)
    {

    }

}//end of function

This function reads a CSV file, load parameters to Datatable and set datasource of grid as Datatable. This is an ASP.NET WebfoRM CODE.