这是一种只读取最后一行而不遍历整个文件的方法。它走到文件的末尾并开始向后读取,直到遇到另一个 LF 字符,这表示倒数第二行的结尾,然后它只是读入该行。
在具有数百万行的大文件上,这降低了读取几个字节的成本。
您可以取消注释 Dts.Events.FireInformation 代码在输出窗口中发生的事情。
Dim i As Integer
Dim CurrentByte As Integer
Dim Trailer As String
i = 1
Using reader As StreamReader = New StreamReader("c:\temp\SourceFile.txt")
Do While CurrentByte <> 10 'while we are not finding the next LF character
reader.BaseStream.Seek((-1 * i) - 2, SeekOrigin.End) 'seeking backwards from the last position in the file minus the last CRLF
'Dts.Events.FireInformation(0, "Now at position", reader.BaseStream.Position().ToString, "", 0, False)
CurrentByte = reader.BaseStream.ReadByte 'read the next byte, this will advance pointer position
'Dts.Events.FireInformation(0, "Current ASCII Code", CurrentByte & " Character:" & Chr(CurrentByte), "", 0, False)
i = i + 1 'go to the next character
Loop
Trailer = reader.ReadLine 'we exited on the LF character, so we are at the beginning of trailer line
Dts.Events.FireInformation(0, " Trailer:", Trailer, "", 0, False)
End Using