Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to read a CSV file and store the values into an array in C#?
A CSV file is a comma-separated values file that stores data in a tabular format. Most business organizations use CSV files to store and exchange structured data because of their simplicity and wide compatibility.
In C#, we can read CSV files using the StreamReader class along with File.OpenRead() method. The data can then be parsed and stored in arrays or collections for further processing.
Syntax
Following is the basic syntax for reading a CSV file −
StreamReader reader = new StreamReader(File.OpenRead(filePath));
while (!reader.EndOfStream) {
var line = reader.ReadLine();
var values = line.Split(',');
}
Reading CSV into a List
This example demonstrates how to read a CSV file and store all values into a single list −
using System;
using System.Collections.Generic;
using System.IO;
class Program {
public static void Main() {
// Create sample CSV content in memory
string csvContent = "A,B,C\nName,Age,City\nJohn,25,NewYork";
string[] lines = csvContent.Split('<br>');
List<string> allValues = new List<string>();
foreach (string line in lines) {
var values = line.Split(',');
foreach (var item in values) {
allValues.Add(item);
}
}
Console.WriteLine("All CSV values:");
foreach (var value in allValues) {
Console.WriteLine(value);
}
}
}
The output of the above code is −
All CSV values: A B C Name Age City John 25 NewYork
Reading CSV into a 2D Array
For better data organization, we can store CSV data in a two-dimensional array where each row represents a CSV line −
using System;
using System.IO;
class Program {
public static void Main() {
string csvContent = "Name,Age,City\nJohn,25,NewYork\nAlice,30,London\nBob,22,Paris";
string[] lines = csvContent.Split('<br>');
// Create 2D array
string[,] csvData = new string[lines.Length, 3]; // 4 rows, 3 columns
for (int i = 0; i < lines.Length; i++) {
string[] values = lines[i].Split(',');
for (int j = 0; j < values.Length; j++) {
csvData[i, j] = values[j];
}
}
// Display data in tabular format
Console.WriteLine("CSV Data in 2D Array:");
for (int i = 0; i < lines.Length; i++) {
for (int j = 0; j < 3; j++) {
Console.Write(csvData[i, j].PadRight(12));
}
Console.WriteLine();
}
}
}
The output of the above code is −
CSV Data in 2D Array: Name Age City John 25 NewYork Alice 30 London Bob 22 Paris
Reading CSV from File with Error Handling
This example shows how to properly read a CSV file from disk with proper error handling −
using System;
using System.Collections.Generic;
using System.IO;
class Program {
public static void Main() {
// Simulate CSV file content (in real scenario, this would be a file path)
string csvContent = "Product,Price,Stock\nLaptop,999.99,15\nMouse,25.50,50\nKeyboard,75.00,30";
try {
List<string[]> csvRows = new List<string[]>();
string[] lines = csvContent.Split('<br>');
foreach (string line in lines) {
if (!string.IsNullOrEmpty(line)) {
string[] values = line.Split(',');
csvRows.Add(values);
}
}
Console.WriteLine("CSV file read successfully!");
Console.WriteLine($"Total rows: {csvRows.Count}");
Console.WriteLine("\nData:");
foreach (var row in csvRows) {
Console.WriteLine(string.Join(" | ", row));
}
} catch (Exception ex) {
Console.WriteLine($"Error reading CSV: {ex.Message}");
}
}
}
The output of the above code is −
CSV file read successfully! Total rows: 3 Data: Product | Price | Stock Laptop | 999.99 | 15 Mouse | 25.50 | 50 Keyboard | 75.00 | 30
Key Points
Use
StreamReaderwithFile.OpenRead()to read CSV files from disk.The
Split(',')method separates comma-delimited values.Store data in
List<string>for simple storage orstring[,]for tabular structure.Always include error handling when working with file operations.
Consider using
usingstatement for proper resource disposal in production code.
Conclusion
Reading CSV files in C# can be accomplished using StreamReader and string manipulation methods. The data can be stored in various formats like lists, arrays, or custom objects depending on your application's needs. Always include proper error handling when working with file operations.
