阅读C#百万行

Gio*_*eri 5 c# text row line streamreader

我有一个很长的文本文件.所有行都具有相同的长度.我想在C#中读取百万行而没有先读取之前的999999行,否则程序会变得太慢.我能怎么做?

jdw*_*eng 17

试试这个

const int BYTES_PER_LINE = 120;
static void Main(string[] args)
{
    StreamReader reader = new StreamReader("FileName", Encoding.UTF8);
    long skipLines = 999999;

    reader.BaseStream.Position = skipLines * BYTES_PER_LINE;
}?
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 5

你知道每行的字节数吗?

NB知道字符数是不够的.

如果你知道它是固定数量的字节使用:

using( Stream stream = File.Open(fileName, FileMode.Open) )
{
    stream.Seek(bytesPerLine * (myLine - 1), SeekOrigin.Begin);
    using( StreamReader reader = new StreamReader(stream) )
    {
        string line = reader.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果没有,那么:

string line = File.ReadLines(FileName).Skip(999999).Take(1).First();
Run Code Online (Sandbox Code Playgroud)

虽然第二个选项仍然需要枚举行,但它可以避免将整个文件一次性读入内存中以便这样做.

  • 请解释这段代码如何解决"没有先阅读之前的999999"? (8认同)