简体   繁体   中英

How do I read a specific line of text from a TXT file in VB.NET?

So say I wanted to MsgBox line 5 of a txt file, how would I do that? I've Googled for ages, but I can't seem to find anything of use to me.

You can use System.IO.File.ReadLines and Enumerable.ElementAtOrDefault :

Dim line5 = File.ReadLines(pathToFile).ElementAtOrDefault(4)
If line5 IsNot Nothing Then
    MessageBox.Show(line5)
End If

You need to add Imports System.Linq for the LINQ extension methods.

You can use the StreamReader class and only have to look the line(s) you want

Dim fileReader As System.IO.StreamReader
fileReader =My.Computer.FileSystem.OpenTextFileReader("C:\\testfile.txt")
Dim stringReader As String
Dim linenum as Integer=0
While not fileReader.EndOfStream()
    stringReader = fileReader.ReadLine()
    linenum = linenum + 1
    If linenum = 5 Then
        MsgBox(stringReader)
        Exit While  'If you are done here
    End If
End While

Hope it helps

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM