【问题标题】:How to read a big file piece by piece in C# [duplicate]如何在C#中逐个读取一个大文件[重复]
【发布时间】:2014-09-15 04:55:14
【问题描述】:

有一个很大的文本文件。我无法用File.ReadAllText() 方法阅读它。如何在 C# 中逐段阅读?

【问题讨论】:

  • 首先是文本文件吗?如果是,您可以使用流阅读器逐行读取文件。请参阅 MSDN 了解 streamreader 和 readline
  • @paqogomez 请保持建设性。

标签: c#


【解决方案1】:

试试这样的。

在这里,我以 2 兆字节为单位读取文件。

这将减少加载文件和读取的负载,因为它以 2 兆字节的块读取。

如果需要,您可以将大小从 2 兆字节更改为以往任何时候。

using (Stream objStream = File.OpenRead(FilePath))
{
    // Read data from file
    byte[] arrData = { };

    // Read data from file until read position is not equals to length of file
    while (objStream.Position != objStream.Length)
    {
        // Read number of remaining bytes to read
        long lRemainingBytes = objStream.Length - objStream.Position;

        // If bytes to read greater than 2 mega bytes size create array of 2 mega bytes
        // Else create array of remaining bytes
        if (lRemainingBytes > 262144)
        {
            arrData = new byte[262144];
        }
        else
        {
            arrData = new byte[lRemainingBytes];
        }

        // Read data from file
        objStream.Read(arrData, 0, arrData.Length);

        // Other code whatever you want to deal with read data
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2018-02-03
    • 1970-01-01
    • 2015-05-19
    • 2020-02-21
    • 2014-06-22
    • 2021-09-07
    • 2023-04-09
    相关资源
    最近更新 更多