VB.NET使用StreamReader读取文本文件时如何获取对应行的索引
实现方案
你可以通过两种方式在读取文件的循环中实时获取行索引,同时我修正了你原有代码里首次循环line未初始化就调用StartsWith的空引用问题:
方式1:单独声明索引变量跟踪(可读性最高)
Dim lines As New List(Of String) Dim currentIndex As Integer = 0 ' 初始化行索引,从0开始计数 Using reader As New StreamReader(My.Application.Info.DirectoryPath & "\Data.txt") Dim line As String = reader.ReadLine() ' 先读取第一行避免空引用 Do Until line Is Nothing OrElse line.StartsWith(endPrefix) ' 此处currentIndex就是当前行对应的数组索引,可直接使用 ' 例如你要给文本框赋值当前行索引:TextBox1.Text = currentIndex.ToString() lines.Add(line) line = reader.ReadLine() currentIndex += 1 ' 每读完一行索引自增 Loop End Using
方式2:复用List的Count属性(不用额外加变量)
因为List的索引从0开始,每加入一行后Count会自增,所以你要加入的下一行的索引就等于当前的lines.Count:
Dim lines As New List(Of String) Using reader As New StreamReader(My.Application.Info.DirectoryPath & "\Data.txt") Dim line As String = reader.ReadLine() Do Until line Is Nothing OrElse line.StartsWith(endPrefix) ' 此处lines.Count就是当前行对应的数组索引,可直接使用 ' 例如你要给文本框赋值当前行索引:TextBox1.Text = lines.Count.ToString() lines.Add(line) line = reader.ReadLine() Loop End Using
两种方式都可以在读文件的过程中直接拿到对应行的数组索引,不需要后续再遍历整个数组查找,效率更高。
内容的提问来源于stack exchange,提问作者user16526006
相关产品推荐
相关产品推荐

