vbnet 读取文本读取第二行第2个数据全局可以调用第2个数据
在VB.NET中,可以使用StreamReader类来读取文本文件,并使用Split方法来分割每一行的数据。以下是一个示例代码,用于读取文本文件的第二行,并将第二个数据保存为全局变量:
Imports System.IO
Module Module1
Public SecondData As String ' 全局变量,用于保存第二个数据
Sub Main()
ReadTextFile("C:\path\to\textfile.txt")
Console.WriteLine("Second Data: " & SecondData)
Console.ReadLine()
End Sub
Sub ReadTextFile(filePath As String)
Dim lineNumber As Integer = 1 ' 当前行数
Dim lineData As String ' 当前行的数据
Using reader As New StreamReader(filePath)
While Not reader.EndOfStream
lineData = reader.ReadLine()
If lineNumber = 2 Then
Dim dataArr As String() = lineData.Split(" "c) ' 使用空格分割数据
If dataArr.Length >= 2 Then
SecondData = dataArr(1) ' 保存第二个数据
End If
Exit While ' 读取到第二行后,退出循环
End If
lineNumber += 1
End While
End Using
End Sub
End Module
在上述示例代码中,ReadTextFile函数用于读取文本文件,并在第二行时将第二个数据保存到全局变量SecondData中。在Main函数中,我们可以调用SecondData来访问第二个数据。请将示例代码中的"C:\path\to\textfile.txt"替换为实际的文本文件路径
原文地址: https://www.cveoy.top/t/topic/ihPv 著作权归作者所有。请勿转载和采集!