Windows Forms: How to read .csv file in C#

This post shows you How to read CSV file into datatable and show data in DataGridView using C# .NET Windows Forms Application.

To play demo, you should create a new Windows Forms Application by clicking New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadCsvFile" and then click OK button.

c# read csv file

Dragging DataGridView and Button controls from the Visual Toolbox to your form designer, then design your form as shown below.

read csv file in c#

C# csv to datatable oledb

Creating a ReadCsv method that allows you to read data from csv file into DataTable in c#.

//oledb csv parser
public DataTable ReadCsv(string fileName)
{
    DataTable dt = new DataTable("Data");
    using (OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
        Path.GetDirectoryName(fileName) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)';"))
    {
        //Execute select query
        using (OleDbCommand cmd = new OleDbCommand(string.Format("select *from [{0}]", new FileInfo(fileName).Name), cn))
        {
            cn.Open();
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd))
            {
                adapter.Fill(dt);
            }
        }
    }
    return dt;
}

You can easily parse your csv file to DataTable using OleDb in c#.

oledb csv connection string

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +  Path.GetDirectoryName(fileName) + "\";Extended Properties='text;HDR=yes;FMT=Delimited(,)';"

Adding a click event handler to the Open button allows you to load data from csv file to DataGridView.

//Read CSV file and fill into DataTable C#
private void btnOpen_Click(object sender, EventArgs e)
{
    try
    {
        //Open file dialog, allows you to select a csv file
        using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "CSV|*.csv", ValidateNames = true, Multiselect = false })
        {
            if (ofd.ShowDialog() == DialogResult.OK)
                dataGridView.DataSource = ReadCsv(ofd.FileName);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Through this c# example, I hope so you've learned how to read csv file in c# windows application. From there, you can apply to your real projects.

VIDEO TUTORIAL