我已经编写了这段代码,试图将文本文件加载到表单中但是我一直在计数变量上出现溢出错误?
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim fdlg As OpenFileDialog = New OpenFileDialog()
Dim count, i As Integer
count = 0
fdlg.Title = "Open text file to read"
fdlg.InitialDirectory = "c:\"
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
If fdlg.ShowDialog() = DialogResult.OK Then
If System.IO.File.Exists(fdlg.FileName) = True Then
Dim objReader As New System.IO.StreamReader(fdlg.FileName)
Do While objReader.Peek() <> -1
count = count + 1 'Overflow Error?
Loop
Dim myArray(count) As String
For i = 0 To i = count
myArray(i) = objReader.ReadLine()
Next i
For i = 0 To count
TextBox1.Text = myArray(i) & vbNewLine
Next i
objReader.Close()
Else
MsgBox("File Does Not Exist")
End If
End If
End Sub
答案 0 :(得分:0)
同意@Plutonix,Peek()读取下一个字符,但不移动光标。因此,您可能无限循环并导致Integer数据类型溢出。如果您只使用计数来调整数组大小,则可能有更有效的方法来读取文件:
Dim objReader As New System.IO.StreamReader("")
Dim myStrings As New List(Of String)
While Not objReader.EndOfStream()
myStrings.Add(objReader.ReadLine())
End While
For Each aString In myStrings
Textbox1.text &= aString & vbNewLine
Next
甚至更好,使用字符串构建器,因为它更有效率,特别是如果您尝试添加到文本框,逐行添加到文本框是非常低效的,可以让您的应用程序运行与使用stringbuilder相比,速度非常慢:
Dim objReader As New System.IO.StreamReader("")
Dim myStrings As New System.Text.StringBuilder
While Not objReader.EndOfStream()
myStrings.AppendLine(objReader.ReadLine())
End While
Textbox1.text = myStrings.ToString()
答案 1 :(得分:0)
这是我提出的解决方案。我现在的问题是,什么样的智能拆分功能&#34; Delimiter&#34;是否可用于确保只有一个字存储在数组元素中?鉴于将存在随机文本文件格式:即每行一个字,每行多个字或具有空格的行。
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Dim fdlg As OpenFileDialog = New OpenFileDialog()
Dim count, i As Integer
Dim textLine As String
count = 0
fdlg.Title = "Open text file to read"
fdlg.InitialDirectory = "c:\"
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
If fdlg.ShowDialog() = DialogResult.OK Then
If System.IO.File.Exists(fdlg.FileName) = True Then
Dim objReader As New System.IO.StreamReader(fdlg.FileName)
textLine = objReader.ReadToEnd()
Dim myArray() As String = Split(textLine, vbCrLf)
'For i = 0 To myArray.Length - 1
TextBox1.Text = myArray(6) 'A test to see if myArray is populated
' Next i
objReader.Close()
Else
MsgBox("File Does Not Exist")
End If
End If
End Sub