【问题标题】:How can I fix this NRE when trying to read .txt file?尝试读取 .txt 文件时如何修复此 NRE?
【发布时间】:2021-06-25 01:43:33
【问题描述】:

我有这个代码:

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

【问题讨论】:

  • 您应该先阅读当前行,然后再选择该文本的目的地。您最好事先阅读所有行,使用List(Of String) 作为容器,然后使用LINQ 的.Where(...).ToArray() 将文本行分配给控件(设置DataSource 或使用Items.AddRange() 方法)。 -- 您应该指定这些 ListBox 控件属于哪个 UI 平台。
  • 您的部分问题是您为每个案例调用 Read Line 两次。正如@Jimi 所说,在对其进行任何处理之前将该行读入某种性质的变量

标签: vb.net text-files nullreferenceexception


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多