一次从文件中读取多行

Read several lines from file at once

以下代码工作正常:

Function ReadLines(FN As String, n As Integer) As String()
    Dim T(0 To n) As String
    With My.Computer.FileSystem.OpenTextFileReader(FN)
        For i As Integer = 0 To n
            T(i) = .ReadLine()
        Next
    End With
    Return T
End Function

但是,如果文件位于远程服务器上,这可能会非常慢。有没有办法更有效地做同样的事情?我也可以一次读取整个文件,但这也相当低效...

Dim lines = IO.File.ReadLines(fileName).
                    Skip(firstLineIndex).
                    Take(lineCount).
                    ToArray()

File.ReadAllLines 方法不同,File.ReadLines 不会在一次操作中读取整个文件。它将文件的内容公开为 Enumerable(Of String) 但在您使用它之前不会从文件中读取任何内容。该代码必须读取每一行,直到您想要的最后一行,但不会读取超出此范围的任何内容。

老实说,我不确定它会快多少,因为它实际上可能在幕后使用 StreamReader.ReadLine。不过值得测试。另一种方法是只读取文件的较大块并自己将其分成几行,当您至少阅读了所需的内容时停止。

BufferedStream class是专门为了减少连续读取(或写入)一个文件时的系统IO次数而设计的。因此,这有望使您的阅读更有效:

Function ReadLines(FN As String, n As Integer) As String()
    Using fs As FileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        Using bs As New BufferedStream(fs)
            Using sr As New StreamReader(bs)
                Dim lines = New List(Of String)(n)
                For i As Integer = 0 To n
                    Dim line As String = sr.ReadLine()
                    If (line Is Nothing) Then
                        Exit For
                    End If
                    lines.Add(line)
                Next
                Return lines.ToArray()
            End Using
        End Using
    End Using
End Function