Reading last lines of a text file?

fracmak

New member
Joined
Jul 13, 2003
Messages
3
Im writing a program in Visual Basic .NET and I was wondering if there was a way to jump to the end of a text file and only read in somewhere between the last 10 to 20 lines of it. I want to do this without reading in the entire text file through a stream reader because these text files can be very large and I only care about the last few lines of it. Does anyone have any suggestions? Ive tried using the SEEK command to jump to the end of a file but after that Im not sure how to get the file input to read characters backwards.
 
well you could do something like this if you wanted.

sr as new streamreader.
a =0
Do Until a=line number you want to start at
sr.ReadLine
Loop

In the loop simply doing nothing with the data. If it requires you to do something with it, make a fake string and kill it afterward. And then sr.ReadLine would start on the line you want to read.


Kevin Heeney


or something like that where you could
 
I dont know if you can step through the stream backwards, but you can use the seek method with a negative offset to start reading 500 bytes before the end of the text file.

[VB]
Dim sr As New System.IO.StreamReader("C:\Test\MyText.txt")
Dim LastLines as String
sr.BaseStream.Seek(-500, IO.SeekOrigin.End)
Do Until sr.Peek = -1
LastLines &= sr.Read.ToString
Loop
[/VB]

Hope that helps.
 
Well, the first problem is that doing sr.ReadLine still reads from the file instead of skipping to the end of the file. The second problem is I tried using the SEEK command but its hard to decide how many bytes back will give you 20 lines of text. I tried to read the characters backwards by doing a sr.READ(), then SEEK(-2, IO.SeekOrigin.Current), wash, rinse, repeat. But it was acting really weird and giving me the characters kinda out of order. Like if I had the string "Version", it would give me "Vrisn". Was hoping there was some other solution I hadnt found yet.
 
Does the text that youre trying to extract from these different text files always start the same way? In other words, if your target text always starts in some recognizable way (which I suspect it must), then you could seek to 1000 bytes (or whatever length would ensure that youd be grabbing all of the target text) before the end, and then do some string manipulation to chop off the leading characters that you dont want. So if your target text always starts with the words "END BLOCK", then you could do:

[VB]
Dim sr As New StreamReader("c:\Test\MyTextFile.txt")

Dim LastLines As String
Dim FirstWord As String = "END BLOCK"
sr.BaseStream.Seek(-1000, SeekOrigin.End)

LastLines = sr.ReadToEnd

LastLines = LastLines.Substring(LastLines.IndexOf(FirstWord))

[/VB]

Good luck.
 
Back
Top