How to Read CSV File in C# - Simple Guide
To read a CSV file in C#, use
System.IO.File.ReadAllLines to get all lines, then split each line by commas with string.Split(','). This lets you process each row and column easily in your program.Syntax
Use File.ReadAllLines(path) to read all lines from a CSV file into a string array. Then, use line.Split(',') to separate each line into columns.
path: The file path to your CSV file.ReadAllLines: Reads all lines at once.Split: Divides each line into parts by commas.
csharp
string[] lines = File.ReadAllLines("file.csv"); foreach (string line in lines) { string[] columns = line.Split(','); // Process columns }
Example
This example reads a CSV file named data.csv with two columns: Name and Age. It prints each row's values to the console.
csharp
using System; using System.IO; class Program { static void Main() { string path = "data.csv"; string[] lines = File.ReadAllLines(path); foreach (string line in lines) { string[] columns = line.Split(','); string name = columns[0]; string age = columns[1]; Console.WriteLine($"Name: {name}, Age: {age}"); } } }
Output
Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Charlie, Age: 35
Common Pitfalls
Common mistakes when reading CSV files include:
- Not handling empty lines or missing columns, which can cause errors.
- Assuming commas are the only separator; some CSVs use semicolons or tabs.
- Not trimming spaces around values, leading to unexpected whitespace.
- Ignoring quoted fields that contain commas inside them.
For simple CSVs, Split(',') works, but for complex files, consider using a CSV parsing library.
csharp
/* Wrong way: Not checking columns length */ string[] columns = line.Split(','); string name = columns[0]; string age = columns[1]; // May throw error if columns missing /* Right way: Check columns length */ string[] columns = line.Split(','); if (columns.Length >= 2) { string name = columns[0].Trim(); string age = columns[1].Trim(); // Use values safely }
Quick Reference
Tips for reading CSV files in C#:
- Use
File.ReadAllLinesfor small files. - Use
Split(',')to separate columns. - Trim values to remove extra spaces.
- Check array length before accessing columns.
- For complex CSVs, use libraries like
CsvHelper.
Key Takeaways
Use File.ReadAllLines to read all lines from a CSV file at once.
Split each line by commas to get individual columns.
Always check the number of columns before accessing to avoid errors.
Trim column values to clean extra spaces.
For complex CSV formats, use a dedicated CSV parsing library.