【问题标题】:The difference between StreamReader.ReadLine and File.ReadLines? [closed]StreamReader.ReadLine 和 File.ReadLines 的区别? [关闭]
【发布时间】:2013-11-29 14:06:08
【问题描述】:

我试图将文件拆分为大约 1GB 我不知道有什么方法可以做到这一点? StreamReader.ReadLine 还是 File.ReadLines?

请注意,我不会将所有数据文件都放在内存中,因为它需要更多内存。

【问题讨论】:

  • StreamReader 更灵活,因为它还有其他 Read... 方法。 ReadLines 仅按行拆分。所以我会尽可能使用ReadLines,如有必要,我会使用StreamReader

标签: c# split


【解决方案1】:

File.ReadLines 在内部创建ReadLinesIterator,它使用StreamReader.ReadLine() 在枚举行时逐行读取文件:

internal class ReadLinesIterator : Iterator<string>
{
    private StreamReader _reader;

    public override bool MoveNext()
    {
        if (this._reader != null)
        {
            base.current = this._reader.ReadLine();
            if (base.current != null)
                return true;

            base.Dispose();
        }
        return false;
    }
}

因此,不同之处在于 - StreamReader.ReadLine() 从流中读取单行。 File.ReadLines 遍历所有行(直到您停止)并使用 StreamReader.ReadLine() 从流中读取每一行。

【讨论】:

    【解决方案2】:

    ReadAllLines 一次读取文件中的所有行。 StreamReaders ReadLine 逐行读取它,但您必须自己遍历文件,直到没有更多行可读取。 当您阅读某些内容时……当然,无论如何,它都会在内存中。

    【讨论】:

    • 实际上File.ReadLines 的执行方式不同,它只会读取您需要的行。你把它和File.ReadAllLines混在一起了
    • 很好 - 我的困惑是 ReadLines 和 ReadAllLines
    猜你喜欢
    • 2014-03-25
    • 2018-12-30
    • 1970-01-01
    • 2012-12-16
    • 2011-12-30
    • 2014-11-01
    • 2013-08-07
    • 2016-12-17
    • 2020-06-09
    相关资源
    最近更新 更多