how can i jump into some line in my file, e.g line 300 in c:\text.txt?
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
}
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With