Public Group

# Read file from back C#

This topic is 2693 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello,
I have a huge text file, and reading it from the start line by line is not very efficient. So I want to read a text from from the back because I am looking for the most recent information added to it. My target is to read about 20 lines from the back and put each line in a string array for later comparison. The closest thing I have seen is this: http://msdn.microsoft.com/en-us/library/system.io.filestream.seek.aspx which uses the seek method. But the examples here read from the back character by character. I want to read using line by line.
Is there a way to do this using System.IO.StreamReader?

Thanks!

##### Share on other sites
AFAIK there is not a way to directly do what you want in .NET.

You should specify an arbitrary position (say, 10 kilobytes from end), split in lines, and if you have read less than 21 lines double the distance from end and try again.

int length = 10240 / 2; do { length = length * 2; sr.Seek(-length, SeekOrigin.End); String data = sr.ReadToEnd(); String[] lines = data.Split("\n"); } while (lines.Count < 21 or length > fileSize);

I use 21 because if you just read 20, the first one could be incomplete. Then you must discard the excess lines.
This is not the best method but it's very simple. The code won't work as is, but hopefully you'll get the idea.

Anyway, what does "huge" means? Have you tried to read it forward? Do you read it more than once? In other words, are you *really* sure it's a problem?

Good luck!

##### Share on other sites
If the log is really too big, stop storing it all in one file. But that's probably not the case.

Just read the whole text file into a string, and operate on it in memory. Then you can split it into lines using the tokenizer functions. Or you can read it a line at a time into an array structure and grab the last 20.

1. 1
2. 2
Rutin
21
3. 3
4. 4
frob
15
5. 5

• 9
• 13
• 9
• 33
• 13
• ### Forum Statistics

• Total Topics
632593
• Total Posts
3007281

×