在VB(Visual Basic)中读取TXT文本,可以使用以下几种方法:
方法一:使用 `Input` 语句
```vb
Dim sr As System.IO.StreamReader = New System.IO.StreamReader("C:\sample.txt")
Dim line As String
line = sr.ReadLine()
While line IsNot Nothing
' 处理每一行数据
line = sr.ReadLine()
Loop
sr.Close()
```
方法二:使用 `Open` 语句和 `Line Input `
```vb
Dim FreeNum As Integer = FreeFile ' 获取一个空闲的文件号
Open "C:\sample.txt" For Input As FreeNum ' 以输入方式打开文件
Do Until EOF(FreeNum) ' 循环直到文件结尾
Line Input FreeNum, line ' 读取一行数据
' 处理每一行数据
Loop
Close FreeNum ' 关闭文件
```
方法三:使用 `StreamReader` 类
```vb
Dim path As String = "C:\sample.txt"
Dim sr As New System.IO.StreamReader(path)
Dim line As String
line = sr.ReadLine()
While line IsNot Nothing
' 处理每一行数据
line = sr.ReadLine()
Loop
sr.Close()
```
方法四:读取指定行内容
```vb
Sub 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 Sub
```
方法五:写入文件
如果需要同时进行读取和写入操作,可以使用以下方法:
```vb
Dim path As String = "C:\sample.txt"
Dim sr As New System.IO.StreamReader(path)
Dim line As String
line = sr.ReadLine()
While line IsNot Nothing
' 处理每一行数据
line = sr.ReadLine()
Loop
sr.Close()
' 写入新行
Dim writer As New System.IO.StreamWriter(path)
writer.WriteLine("新的一行")
writer.Close()
```
这些方法可以帮助你在VB中读取TXT文件的内容。根据具体需求选择合适的方法即可。