I was wondering if/how you can read a specific line in vb.net using a system.io.streamreader.
Dim streamreader as system.io.streamreader
streamreader.selectline(linenumber as int).read
streamreader.close()
Is this possible or is there a similiar function to this one?
I'd use File.ReadAllLines
to read in the lines into an array, then just use the array to select the line.
Dim allLines As String() = File.ReadAllLines(filePath)
Dim lineTwo As String = allLines(1) '0-based index
Note that ReadAllLines
will read the entire text file into memory but I assume this isn't a problem because, if it is, then I suggest you take an alternative approach to trying to jump to a specific line.
ReadLines
is pretty fast as it doesn't load everything in memory. It returns an IEnumerable<string>
which allow you to skip to a line easily. Take this 5GB file:
var data = new string('A', 1022);
using (var writer = new StreamWriter(@"d:\text.txt"))
{
for (int i = 1; i <= 1024 * 1024 * 5; i++)
{
writer.WriteLine("{0} {1}", i, data);
}
}
var watch = Stopwatch.StartNew();
var line = File.ReadLines(@"d:\text.txt").Skip(704320).Take(1).FirstOrDefault();
watch.Stop();
Console.WriteLine("Elapsed time: {0}", watch.Elapsed); // Elapsed time: 00:00:02.0507396
Console.WriteLine(line); // 704320 AAAAAA...
Console.ReadLine();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.