Private Function GetNextLineReversed(ByVal lngStartPos As Long) As String
************************************************************************
** GET NEXT LINE REVERSED **
** ------------------------------------------------------------------ **
** Returns a text line backwards from a file, starting at lngStartPos **
** Returns "eof" if no lines found **
************************************************************************
Try
Dim myReader As New System.IO.StreamReader(myFileStream, System.Text.Encoding.Default)
Dim temp As String = ""
Dim sTempLine As String = ""
Dim TempBlock(0) As Char
Dim cBuffer(0) As Byte
Dim lngLastLineStartPos As Long
Dim lngLastLineEndPos As Long
Goto lngStartPos, step back to previous line
Save for end of line
lngLastLineEndPos = lngStartPos - 2
If lngLastLineEndPos < 1 Then no can do, this would get us to -1 in next statement
Return "eof"
End If
Loop to find first vbLF reversed
myFileStream.Position = lngLastLineEndPos - 1
myFileStream.Read(cBuffer, 0, 1)
Do While Not ChrW(cBuffer(0)) = vbLf And myFileStream.Position > 1
temp = temp & ChrW(cBuffer(0))
myFileStream.Position = myFileStream.Position - 2
myFileStream.Read(cBuffer, 0, 1)
Loop
Save for start of line
lngLastLineStartPos = myFileStream.Position
Clear variables
TempBlock = ""
sTempLine = ""
Get the line from lngLastLineEndPos to lngLastLineStartPos
ReDim TempBlock(lngLastLineEndPos - lngLastLineStartPos)
myFileStream.Position = lngLastLineStartPos
myReader.ReadBlock(TempBlock, 0, lngLastLineEndPos - lngLastLineStartPos)
sTempLine = TempBlock
here you can save the start position of the last line parsed
save it in a global variable to use it as a new start posistion when calling the GetNextLineReversed() function again
g_lngLastLineStartPosition = lngLastLineStartPos
return the line
Return sTempLine
Catch
insert error handling here
End Try
End Function
To use the function:
----------------------------------------------------
Dim strFileName as string
Dim myFileStream as FileStream
Dim lngStartPos as long
file name and path to parse
strFileName = "c:\test.txt"
Create a global filestream object
myFileStream = New System.IO.FileStream(strFileName,System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite)
go to end of file and save position (stream.length can also be used to find the last byte )
myFileStream.Seek(0, SeekOrigin.End)
lngStartPos = myFileStream.Position
sLine = GetNextLineReversed(lngStartPos)
----------------------------------------------------