Comma Separated Values (CSV) files are a ubiquitous format for storing tabular data. This article presents two efficient C# methods for reading CSV files and storing their contents in arrays. We’ll explore a manual approach using the StreamReader
class and a more streamlined solution leveraging the TextFieldParser
class from the Microsoft.VisualBasic.FileIO
library.
Table of Contents
Reading CSV Files with StreamReader
The StreamReader
approach offers granular control over the reading process, enabling customization for diverse CSV formats. However, it demands more manual handling of delimiters and error conditions.
using System;
using System.IO;
public class CsvReaderStreamReader
{
public static string[][] ReadCsv(string filePath)
{
string[][] data = new string[0][]; // Initialize as an empty array
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] values = line.Split(',');
Array.Resize(ref data, data.Length + 1);
data[data.Length - 1] = values;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading CSV file: {ex.Message}");
}
return data;
}
public static void Main(string[] args)
{
string filePath = "data.csv";
string[][] csvData = ReadCsv(filePath);
if (csvData != null)
{
foreach (string[] row in csvData)
{
Console.WriteLine(string.Join(" ", row));
}
}
}
}
This improved code dynamically resizes the array, avoiding the arbitrary initial size limitation. It also uses string interpolation for cleaner error messages and string.Join
for concise output.
Reading CSV Files with TextFieldParser
The TextFieldParser
simplifies CSV parsing, especially for complex files with quoted fields or custom delimiters. It handles these intricacies automatically.
using Microsoft.VisualBasic.FileIO;
using System;
public class CsvReaderTextFieldParser
{
public static string[][] ReadCsv(string filePath)
{
string[][] data = new string[0][];
try
{
using (TextFieldParser parser = new TextFieldParser(filePath))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
Array.Resize(ref data, data.Length + 1);
data[data.Length - 1] = fields;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error reading CSV file: {ex.Message}");
}
return data;
}
public static void Main(string[] args)
{
string filePath = "data.csv";
string[][] csvData = ReadCsv(filePath);
if (csvData != null)
{
foreach (string[] row in csvData)
{
Console.WriteLine(string.Join(" ", row));
}
}
}
}
This code efficiently handles the CSV parsing using TextFieldParser
. Remember to add a reference to the Microsoft.VisualBasic
assembly in your project.
Method Comparison
Both methods achieve the same outcome, but TextFieldParser
is generally preferred for its robustness and ease of use, particularly with complex CSV files. StreamReader
offers more control for specialized scenarios, but requires careful error handling and delimiter management.