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);
}
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
--
Shak
(Houston)
Neil Patel said:
I have a log file that puts the most recent record at the bottom of the
file. Each line is delimited by a \r\n
Does anyone know how to seek to the end of the file and start reading
backwards?