How to read CSV file in C#
By FoxLearn 12/10/2024 2:34:14 AM 9.79K
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.
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.
What does a csv file look like?
A CSV (Comma-Separated Values) file is a simple text file used to store tabular data, such as numbers and text, in a plain format. Each line in a CSV file corresponds to a row in the table, and values within each row are separated by commas (or other delimiters, such as semicolons).
For example:
First Name,Last Name,Age,Occupation John,Doe,30,Engineer Jane,Smith,25,Designer Sam,Brown,28,Developer
CSV files are plain text and can be opened in text editors (like Notepad) or imported into spreadsheet programs like Microsoft Excel or Google Sheets.
In this case, quotes are used to enclose values that contain commas, ensuring that the comma inside the address doesn't split the field into multiple columns.
For example:
ID,Name,Address,Phone Number 1,"Lucy","123 Elm St, Apt 5",555-1234
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.
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.