温馨提示×

vb如何读取txt指定行内容

vb
小亿
132
2024-03-21 17:05:45
栏目: 编程语言

要读取txt文件中的指定行内容,您可以使用StreamReader类来实现。以下是一个示例代码,演示如何读取txt文件中第三行的内容:

Imports System.IO

Module Module1
    Sub Main()
        Dim path As String = "C:\sample.txt"
        Dim line As String = ReadSpecificLine(path, 3)
        Console.WriteLine("Line 3: " & line)
    End Sub

    Function ReadSpecificLine(path As String, lineNumber As Integer) As String
        Using reader As New StreamReader(path)
            Dim currentLine As Integer = 0
            Dim line As String = reader.ReadLine()
            While line IsNot Nothing
                currentLine += 1
                If currentLine = lineNumber Then
                    Return line
                End If
                line = reader.ReadLine()
            End While
        End Using
        Return Nothing
    End Function
End Module

在上面的代码中,我们首先定义了一个名为ReadSpecificLine的函数,它接受文件路径和行号作为参数,并返回该行的内容。然后,在Main函数中,我们调用ReadSpecificLine函数来读取指定txt文件的第三行内容,并将其打印到控制台上。

请注意,您需要将示例代码中的路径"C:\sample.txt"更改为您自己的txt文件路径。

0