[英]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? 因此,说我想对txt文件的MsgBox
第5行进行操作,我该怎么做? I've Googled for ages, but I can't seem to find anything of use to me. 我已经使用Google搜索了很长时间,但似乎找不到任何有用的东西。
You can use System.IO.File.ReadLines
and Enumerable.ElementAtOrDefault
: 您可以使用System.IO.File.ReadLines
和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. 您需要为LINQ扩展方法添加Imports System.Linq
。
You can use the StreamReader class and only have to look the line(s) you want 您可以使用StreamReader类,而只需查看所需的行
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 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.