我试图在新项目中使用一个项目的文件。代码在调试时没有错误,但跳过我编程的错误"问题从文件读取数据。"无论如何,任何运行程序的尝试都会导致0的计算 - 因为数组似乎不会填充。
感谢您的帮助。
'opens the text file, reads it, stores the value in two arrays
'closes the file
Dim srFileName As String 'Name the file to be opened
Dim intNumItems As Integer 'number of records on file
Dim i As Integer 'loop counter for the array
Dim intLastBlank As Integer
Dim strInput As String
srFileName = "C:\StudentMarks.txt"
If File.Exists(srFileName) Then
Dim srReader As New StreamReader(srFileName)
Try
intNumItems = srReader.ReadLine()
strInput = srReader.ReadLine()
Do While srReader.Peek >= 0
Loop
strInput = srReader.ReadLine()
While Not srReader.EndOfStream
'each loop iteration, reads 2 lines and places in proper array
For i = 0 To intNumItems - 1
'find location of tab between student name and mark
intLastBlank = strInput.IndexOf(vbTab)
'take characters before tab and place in name array
arrName(i) = strInput.Substring(intLastBlank + 1)
'take characters after tab, convert to double, and
'place values in mark array
arrMark(i) = Double.Parse(strInput.Substring(intLastBlank + 1))
Next
End While
Catch ex As Exception
MessageBox.Show("Problem reading data from file")
End Try
答案 0 :(得分:0)
你真的应该让你的MessageBox显示实际的错误信息。它可以帮助您解决问题。
示例:
MessageBox.Show("Problem reading data from file:" & Environment.NewLine & ex.Message)
无论如何,至于你的问题,你在这里创建了一个无限循环:
Do While srReader.Peek >= 0
'You have no code here, so you've created yourself an infinite loop.
Loop
strInput = srReader.ReadLine()
您可能放错了Loop
关键字。我猜它应该在代码中更进一步?
修改强>
我也不明白使用两者的意义:
Do While srReader.Peek >= 0
...和
While Not srReader.EndOfStream
您只需要使用其中一个语句,因为它们都会检查StreamReader
是否有更多内容。
还要确保将.ReadLine()
方法放在循环中。 :)