逗号分隔值 (CSV) 文件是存储表格数据的普遍格式。本文介绍了两种高效的 C# 方法,用于读取 CSV 文件并将内容存储在数组中。我们将探讨使用StreamReader
类的手动方法和利用Microsoft.VisualBasic.FileIO
库中的TextFieldParser
类的更简化方案。
目录
使用 StreamReader 读取 CSV 文件
StreamReader
方法提供了对读取过程的细粒度控制,可以针对不同的 CSV 格式进行自定义。但是,它需要更多的手动处理分隔符和错误条件。
using System;
using System.IO;
public class CsvReaderStreamReader
{
public static string[][] ReadCsv(string filePath)
{
string[][] data = new string[0][]; // 初始化为空数组
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($"读取 CSV 文件出错:{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));
}
}
}
}
改进后的代码动态调整数组大小,避免了任意初始大小的限制。它还使用字符串插值来实现更清晰的错误消息,并使用string.Join
来简化输出。
使用 TextFieldParser 读取 CSV 文件
TextFieldParser
简化了 CSV 解析,尤其对于包含带引号的字段或自定义分隔符的复杂文件。它自动处理这些复杂情况。
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($"读取 CSV 文件出错:{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));
}
}
}
}
此代码使用TextFieldParser
高效地处理 CSV 解析。请记住在项目中添加对Microsoft.VisualBasic
程序集的引用。
方法比较
两种方法都达到了相同的结果,但TextFieldParser
由于其健壮性和易用性而通常更受欢迎,尤其是在处理复杂的 CSV 文件时。StreamReader
为特殊场景提供了更多控制,但需要仔细的错误处理和分隔符管理。