c# - 如何使用 StreamReader 分块加载大文件?

标签 c#

我不熟悉使用 C# 读取文件数据。我有一个大文本文件,其中的数据以逗号分隔。我想将此文件加载到我的应用程序中的 DataTable 中(或加载到域对象中),但在执行此操作时出现了 OutOfMemoryException。我尝试了几种不同的方法,但仍然出现相同的错误。似乎为了加载数据我需要以 block 的形式加载它,处理 block 然后存储它,然后获取下一个 block 然后处理它等等

我如何使用 StreamReader 来做到这一点?我如何告诉 StreamReader 在文件中读取到哪里以及它如何知道从哪里继续获取下一个 block ?

最佳答案

您可以使用 Buffer Stream 读取 block 数据,这里是代码

private void ReadFile(string filePath)
{
    const int MAX_BUFFER = 20971520; //20MB this is the chunk size read from file
    byte[] buffer = new byte[MAX_BUFFER];
    int bytesRead;

    using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read))
    using (BufferedStream bs = new BufferedStream(fs))
       {
          while ((bytesRead = bs.Read(buffer, 0, MAX_BUFFER)) != 0) //reading only 20mb chunks at a time
              {
                   //buffer contains the chunk data Treasure the moments with it . . . 
                   //modify the buffer size above to change the size of chunk . . .
              }
       }
}

关于c# - 如何使用 StreamReader 分块加载大文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43594911/

相关文章:

c# - 当 openFileDialog 从第二个表单返回结果时,Modalform 关闭

c# - 添加对 VS2008 项目的 VB6 ActiveX DLL 引用

c# - Unity 防止点击按钮

c# - 使用空日期时间对 DataGridView 进行排序

c# - 在 DataGridView 中处理 TextBox 中的导航键

c# - 如何从 ssl 证书和签名属性调用 Soap web 服务

c# - 如何将负数变为红色?

c# - 下拉列表 selectedindex 更改后显示隐藏的文本框和标签

c# - 构建许多 C# 项目时 Visual Studio Build Avoidance

C# 和 UTF-16 字符