如何使用 C# 读取 CSV 文件?使用 File.ReadAllLines() 读取所有行。使用 StreamReader 逐行读取。使用第三方库(如 CsvHelper)简化读取过程。

如何使用 C# 读取 CSV 文件
CSV(逗号分隔值)是一种流行的数据格式,常用于存储表格数据。在 C# 中,可以使用以下方法读取 CSV 文件:
1. 使用 File.ReadAllLines()
string[] lines = File.ReadAllLines("path/to/file.csv");此方法将读取 CSV 文件的所有行并将其存储在字符串数组 lines 中。
2. 使用 StreamReader
using (StreamReader reader = new StreamReader("path/to/file.csv"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// 处理行数据
}
}此方法使用 StreamReader 类逐行读取 CSV 文件。
3. 使用第三方库(例如 CsvHelper)
可以使用第三方库(如 CsvHelper)来简化 CSV 文件的读取过程。CsvHelper 提供了以下方法:
using CsvHelper;
using (var reader = new CsvReader(new StreamReader("path/to/file.csv")))
{
reader.Configuration.Delimiter = ","; // 设置分隔符
var records = reader.GetRecords(); // 读入记录
} 处理 CSV 数据
读取 CSV 文件后,可以使用以下技术处理数据:
-
分隔行:使用
String.Split()方法以逗号作为分隔符拆分行。 - 解析值:将每个值转换为适当的数据类型,如整数、浮点数或字符串。
- 存储数据:将解析后的值存储在列表、数组或其他数据结构中。
示例
以下是读取 CSV 文件并将其数据存储在列表中的示例代码:
using System.Collections.Generic;
var lines = File.ReadAllLines("path/to/file.csv");
var data = new List>();
foreach (var line in lines)
{
var values = line.Split(',');
data.Add(new List(values));
}










