Shakir Hussain <shak@fakedomain.com> wrote:[color=blue]
> Couple of ways to do that.
>
> Method 1:
>
> //initialize streamreader
> StreamReader myStream= new StreamReader(@"c:\myfile.txt");
> //seek file pointer to end
> myStream.BaseStream.Seek(1024,SeekOrigin.End);
>
> //intialize array of size 1024
> char [] arr = new char[1024];
> //loop now and read backwards
> While(myStream.BaseStream.Position > 0)
> {
> arr.Initialize();
> //Move back 1024 bytes (for better control)
> myStream.BaseStream.Seek(1024,SeekOrigin.Current);
> //read 1024 bytes.
> int bytesRead = myStream.Read(arr,0,1024);
>
> }[/color]
Note that you've got a bit of confusion here between bytes and
characters - a StreamReader returns the number of *characters* read,
not bytes... and that introduces another problem. There's nothing to
say that moving backwards 1024 bytes will even put you at the start of
a character - it could be in the middle of a multi-byte character.
You also need to discard the StreamReader's buffer after repositioning.
Also, the first parameter to Seek should be -1024, not 1024, otherwise
it's moving forwards not backwards.
Finally, moving back 1024 bytes doesn't mean you'll move back 1024
characters, so the code above could mean reading some characters twice.
[color=blue]
> Method:2
>
> //initialize streamreader
> StreamReader myStream = new StreamReader(@"c:\myfile.txt");
> //read all the contents and store in string
> string WholeFileString=myStream.ReadToEnd();
> //convert to array
> char []strArray = WholeFileString.ToCharArray();
> //reverse the array
> Array.Reverse(strArray);
> //again convert to string
> string newStr = new string(strArray);
> //specify the split array (Note \r\n must be specified reverse becoz
> string is reverse
> char [] split = new char[2];
> split[0] = '\n';
> split[1] = '\r';
> //receive the string array after spliting
> string [] Lines = newStr.Split(split);
>
> lines[0] = ; //last line of the file
> lines[lines.Length-1] = ; //first line of the file[/color]
That gives every line of the file reversed as well, which probably
isn't desired. I'd suggest:
ArrayList list = new ArrayList();
using (StreamReader reader = new StreamReader(@"c:\myfile.txt")
{
string line;
while ( (line=reader.ReadLine()) != null)
{
list.Add(line);
}
}
list.Reverse();
That gives you an ArrayList of each line of the file, starting from the
end. It probably doesn't help the OP, however, as I'd assume that the
idea is to avoid having to read the whole file.
--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too