问题描述
我正在将程序从 vb6 迁移到 vb.net。 我有一个要读取多行的文件。
我的代码:
FileOpen(1,FileName,OpenMode.Input)
Do until EOF(1)
Filesystem.input( 1,param1,param2,param3)
Loop
我对这段代码的问题是循环不是“循环”...... 它一遍又一遍地阅读同一行。
使用时:
Do until FileSystem.EOF(1)
strData = Filesystem.LineInput(1)
Loop
循环工作正常。 但是我不能使用它,因为我每行的参数不同,不一致。
有什么问题?为什么不是第一次循环? 是否有其他方法可以解决这个问题?
解决方法
这种代码还有其他方法吗?
一次性将文本文件的所有行读入内存中的数组(假设它是一个文本文件,因为您说的是“多行”):
Dim arr = System.IO.File.ReadAllLines("path here")
'loop over the array
For Each line as String in arr
'... process the line
Next line
要逐行增量读取文件,如果文件很大并且您不想将其全部加载到内存中,请使用 ReadLines 而不是 ReadAllLines:
For Each line as String in System.IO.File.ReadLines("path here")
'... process the line
Next line
,
另一个例子:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click
Dim line As String
Dim values() As String
Dim FileName As String = "c:\someFile.txt"
Using sr As New StreamReader(FileName)
While Not sr.EndOfStream
line = sr.ReadLine()
values = line.Split(",")
End While
End Using
End Sub
End Class
如果您向我们展示文件中的一些示例行,我们可以提供更详细的答案。