Jump to content
  • Advertisement
Sign in to follow this  
musafir2007

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.

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

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?

Please help me find a way to do this.

Thanks!

Share this post


Link to post
Share on other sites
Advertisement
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 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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!