How to read CSV file in C#

By FoxLearn 7/13/2024 1:12:58 AM   9.57K
To read a CSV file in a C# Windows Forms Application, you can follow these steps.

Reading a CSV file in a C# Windows Forms Application you can use the StreamReader class from the System.IO namespace.

How to read csv file in C#

Drag and drop 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 CsvHelper class.

// c# read csv file to datatable
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;
}

Adding a click event handler to the Browse button that 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);
        }
    }
}

Another way, you can read a CSV file in a C# Windows Forms Application involves using the TextFieldParser class from the Microsoft.VisualBasic.FileIO namespace.

First, make sure to add the Microsoft.VisualBasic assembly reference to your project.

To do this, right-click on your project in Solution Explorer, select "Add" -> "Reference...", then select "Microsoft.VisualBasic" from the list.

Next, Import the necessary namespaces in your code file.

using System.IO;
using Microsoft.VisualBasic.FileIO;

Finally, Use the TextFieldParser class to read the CSV file.

Here's an example method to read the CSV file and return its content as a list of string arrays

public List<string[]> ReadCSV(string filePath)
{
    List<string[]> csvData = new List<string[]>();
    // Use TextFieldParser to read the CSV file
    using (TextFieldParser parser = new TextFieldParser(filePath))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(",");
        // Read and parse each line of the CSV file
        while (!parser.EndOfData)
        {
            string[] fields = parser.ReadFields();
            csvData.Add(fields);
        }
    }
    return csvData;
}

Call this method with the file path of your CSV file. It will return a list of string arrays, where each array represents a row of the CSV file.

string filePath = "path/to/your/csv/file.csv";
List<string[]> data = ReadCSV(filePath);
// Now you can iterate through 'data' to access CSV contents
foreach (string[] row in data)
{
    // Access each field in the row
    foreach (string field in row)
        Console.Write(field + ",");
    Console.WriteLine();
}

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.