Line delimited files are not intended for random access. Thus, you need to search for a file by reading and discarding the required number of lines.
Modern approach:
class LineReader : IEnumerable<string>, IDisposable { TextReader _reader; public LineReader(TextReader reader) { _reader = reader; } public IEnumerator<string> GetEnumerator() { string line; while ((line = _reader.ReadLine()) != null) { yield return line; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { _reader.Dispose(); } }
Using:
// path is string int skip = 300; StreamReader sr = new StreamReader(path); using (var lineReader = new LineReader(sr)) { IEnumerable<string> lines = lineReader.Skip(skip); foreach (string line in lines) { Console.WriteLine(line); } }
Simple approach:
string path; int count = 0; int skip = 300; using (StreamReader sr = new StreamReader(path)) { while ((count < skip) && (sr.ReadLine() != null)) { count++; } if(!sr.EndOfStream) Console.WriteLine(sr.ReadLine()); } }
jason
source share