提问人:cam 提问时间:3/29/2021 更新时间:3/30/2021 访问量:50
尝试读取 .txt 文件时如何修复此 NRE?
How can I fix this NRE when trying to read .txt file?
问:
我有这个代码:
Dim TextRead As StreamReader = File.OpenText(FilePath)
Do While TextRead.Peek <> -1
Select Case True
Case TextRead.ReadLine.EndsWith("25m Freestyle") : lstF25.Items.Add(TextRead.ReadLine())
Case TextRead.ReadLine.EndsWith("50m Freestyle") : lstF50.Items.Add(TextRead.ReadLine())
Case TextRead.ReadLine.EndsWith("25m Backstroke") : lstB25.Items.Add(TextRead.ReadLine())
Case TextRead.ReadLine.EndsWith("50m Backstroke") : lstB50.Items.Add(TextRead.ReadLine())
End Select
Loop
TextRead.Close()
它试图做的是读取每行的末尾,并根据行尾的内容将其放入 4 个不同的 ListBox 中,但我在 case 语句中收到了 NullReferenceExeption。
我知道我没有将 NULL 添加到列表框中,因为它不会导致 .EndsWith() 等于 true。
下面是纺织品外观的示例:
John, Smith, 70, 25m Freestyle
Alice, Smith, 73, 50m Freestyle
Bob, Smith, 71, 25m Backstroke
Charlie, Smith, 74, 50m Backstroke
David, Smith, 76, 25m Backstroke
答:
0赞
Zserigta
3/30/2021
#1
在 select case 子句中,您总是在一个循环中多次调用 readline。 正确方法:
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim TextRead As StreamReader = File.OpenText("d:\test.txt")
Do While TextRead.Peek <> -1
Dim line As String = TextRead.ReadLine()
Select Case True
Case line.EndsWith("25m Freestyle") : lstF25.Items.Add(line)
Case line.EndsWith("50m Freestyle") : lstF50.Items.Add(line)
Case line.EndsWith("25m Backstroke") : lstB25.Items.Add(line)
Case line.EndsWith("50m Backstroke") : lstB50.Items.Add(line)
End Select
Loop
TextRead.Close()
End Sub
评论
List(Of String)
.Where(...).ToArray()
Items.AddRange()