vb如何读取txt指定行内容
要读取txt文件中的指定行内容,您可以使用StreamReader类来实现。以下是一个示例代码,演示如何读取txt文件中第三行的内容:
Imports System.IOModule Module1Sub Main()Dim path As String = "C:\sample.txt"Dim line As String = ReadSpecificLine(path, 3)Console.WriteLine("Line 3: " & line)End SubFunction ReadSpecificLine(path As String, lineNumber As Integer) As StringUsing reader As New StreamReader(path)Dim currentLine As Integer = 0Dim line As String = reader.ReadLine()While line IsNot NothingcurrentLine += 1If currentLine = lineNumber ThenReturn lineEnd Ifline = reader.ReadLine()End WhileEnd UsingReturn NothingEnd FunctionEnd Module
在上面的代码中,我们首先定义了一个名为ReadSpecificLine的函数,它接受文件路径和行号作为参数,并返回该行的内容。然后,在Main函数中,我们调用ReadSpecificLine函数来读取指定txt文件的第三行内容,并将其打印到控制台上。
请注意,您需要将示例代码中的路径"C:\sample.txt"更改为您自己的txt文件路径。