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

如何使用 C# 读取 CSV 文件
CSV(逗号分隔值)是一种流行的数据格式,常用于存储表格数据。在 C# 中,可以使用以下方法读取 CSV 文件:
1. 使用 File.ReadAllLines()
<code class="c#">string[] lines = File.ReadAllLines("path/to/file.csv");</code>此方法将读取 CSV 文件的所有行并将其存储在字符串数组 lines 中。
2. 使用 StreamReader
<code class="c#">using (StreamReader reader = new StreamReader("path/to/file.csv"))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
// 处理行数据
}
}</code>此方法使用 StreamReader 类逐行读取 CSV 文件。
3. 使用第三方库(例如 CsvHelper)
可以使用第三方库(如 CsvHelper)来简化 CSV 文件的读取过程。CsvHelper 提供了以下方法:
<code class="c#">using CsvHelper;
using (var reader = new CsvReader(new StreamReader("path/to/file.csv")))
{
reader.Configuration.Delimiter = ","; // 设置分隔符
var records = reader.GetRecords<MyRecord>(); // 读入记录
}</code>处理 CSV 数据
读取 CSV 文件后,可以使用以下技术处理数据:
String.Split() 方法以逗号作为分隔符拆分行。示例
以下是读取 CSV 文件并将其数据存储在列表中的示例代码:
<code class="c#">using System.Collections.Generic;
var lines = File.ReadAllLines("path/to/file.csv");
var data = new List<List<string>>();
foreach (var line in lines)
{
var values = line.Split(',');
data.Add(new List<string>(values));
}</code>
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号