// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.IO; using System.Text; public class MainClass { public static string[] ReadLastNLines(string fnm, int nolin) { FileStream fs = new FileStream(fnm, FileMode.Open, FileAccess.Read); long l = fs.Length; int n = 3000; long ix = l - n; if(ix < 0) { n = n + (int)ix; ix = 0; } fs.Seek(ix, SeekOrigin.Begin); byte[] b = new byte[n]; fs.Read(b, 0, n); fs.Close(); int nl = n; for(int i = 0; i < nolin; i++) { nl = nl - 2; while(nl >= 0 && b[nl] != '\n') nl--; nl++; } StreamReader sr = new StreamReader(new MemoryStream(b, nl, n - nl), Encoding.Default); string[] res = new string[nolin]; for(int i = 0; i < nolin; i++) { res[i] = sr.ReadLine(); } sr.Close(); return res; } public static void Main(string[] args) { string[] lins = ReadLastNLines(@"C:\big.txt", 3); foreach(string lin in lins) { Console.WriteLine(lin); } } }