Jump to content
  • Advertisement
Sign in to follow this  

Read file from back C#

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Please help me find a way to do this.


Share this post

Link to post
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;
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 this post

Link to post
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.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!