C# 中如何使用 StreamReader 进行分块读取 CSV 文件?
时间: 2025-02-11 17:35:31 浏览: 31
在 C# 中,使用 `StreamReader` 进行 CSV 文件的分块读取可以有效地避免一次性加载所有数据带来的内存压力。下面是一种常见的做法:
```csharp
using System;
using System.IO;
public class CSVReaderExample
{
public static void ProcessFile(string filePath)
{
using (var reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// 分割每一行数据为键值对,并按需处理,例如添加到字典中
var values = line.Split(',');
Dictionary<string, string> dictionaryEntry = new Dictionary<string, string>();
foreach (string value in values)
{
if (!dictionaryEntry.ContainsKey(value)) // 可以根据实际需求进行其他操作
{
dictionaryEntry.Add(value);
}
}
// 在这里处理每个读取的记录
// ...
}
}
}
}
```
这个例子中,我们逐行读取文件,每次读取一行就处理一次,而不是一次性将整份文件加载到内存中。这种方法适合处理大型 CSV 文件,可以节省内存资源。
阅读全文
相关推荐


















