Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jump into file line c#

Tags:

c#

.net

file-io

how can i jump into some line in my file, e.g line 300 in c:\text.txt?

like image 812
aharon Avatar asked Jan 20 '10 16:01

aharon


2 Answers

using (var reader = new StreamReader(@"c:\test.txt"))
{
    for (int i = 0; i < 300; i++)
    {
        reader.ReadLine();
    }
    // Now you are at line 300. You may continue reading
}
like image 175
Darin Dimitrov Avatar answered Sep 20 '22 17:09

Darin Dimitrov


Line-delimited files are not designed for random access. Thus, you have to seek through the file by reading and discarding the necessary 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();
        }
    }

Usage:

// 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());
     }
}
like image 34
jason Avatar answered Sep 22 '22 17:09

jason