Windows Forms: Read CSV file in C#

This post shows you how to read csv file in c#, this example helps you create the csv parser in c# windows forms application.

Drag the TextBox, Label, Button and DataGridView controls from the visual studio toolbox to your winform, then design a simple UI that allows you to read csv file in c# as shown below.

c# read csv file

Create the ReadCsvFile method to help you to read the csv file. CSV (Comma Separated Values) is a kind of simple text format, values ​​separated by commas.

Regular CSV format is used to save small spreadsheets like contacts, reports ..etc. To read the csv file in c# you should read all the lines, then split data by commas. Next, you need to add your data to the DataTable, then set the DataSource of DataGridView to the DataTable.

You can also create the csvhelper class to help you read data from the csv file by copying the ReadCsvFile method into the csvhelper class.

public DataTable ReadCsvFile(string file)
{
    DataTable dt = new DataTable();
    using (StreamReader streamReader = new StreamReader(file))
    {
        while (!streamReader.EndOfStream)
        {
            string text = streamReader.ReadToEnd();
            string[] rows = text.Split('\n');
            if (rows.Length > 0)
            {
                //Add columns
                string[] columns = rows[0].Split(',');
                for (int j = 0; j < columns.Count(); j++)
                    dt.Columns.Add(columns[j]);
                //Add rows
                for (int i = 1; i < rows.Count() - 1; i++)
                {
                    string[] data = rows[i].Split(',');
                    DataRow dr = dt.NewRow();
                    for (int k = 0; k < data.Count(); k++)
                        dr[k] = data[k];
                    dt.Rows.Add(dr);
                }
            }
        }
    }
    return dt;
}

Add code to handle the Browse button click event allows you to select the csv file, then read it as the following c# code.

private void btnBrowse_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV file|*.csv" })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            dataGridView1.DataSource = ReadCsvFile(ofd.FileName);
        }
    }
}

Press F5 to run you project, then select the csv file to play the demo. You can create the sample csv file by exporting data from the sql server database.