StreamReader仅从MultiLine,Spaced文本文件读取和输出最后一行

问题描述 投票:0回答:1

我正在尝试从文本文件中读取值并将它们输入到一个数组中,我可以将它们分配给文本框。我的文本文件的第一行是标题名称(字符串/字符),所有后续行都包含数字:

有多行,每个值由空格分隔。我目前的代码是:

If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
     Dim openreader As System.IO.StreamReader = New System.IO.StreamReader(openFileDialog1.FileName)
    Try

        While Not openreader.EndOfStream
            Dim currentline As String
            currentline = openreader.ReadLine()
            currentline = currentline.Trim(" "c)
            Dim inputparts() As String = currentline.Split(" "c)
            TextBox1.Text = inputparts(0)
            TextBox2.Text = inputparts(1) 'This gives out of bounds error
            TextBox3.Text = inputparts(2) 'This gives out of bounds error
            TextBox4.Text = inputparts(3) 'This gives out of bounds error
        End While

    Catch Ex As Exception
        MessageBox.Show("The file could not be read. The original error is: " & Ex.Message)
    End Try
    openreader.Close()
    End If

这个问题是数组inputparts对于高于inputparts(0)和inputparts(0)的任何东西都有一个越界错误,这是唯一记录的元素,它始终是最后一行的最后一个数字。我不想定义inputparts()的维度,因为我是我的输入文件,可以自由地拥有一系列不同的值。

为什么数组没有记录除最后一个以外的任何值 - 是因为我的当前行最终成为最后一行 - 我该如何解决这个问题?任何帮助,将不胜感激!

vb.net streamreader
1个回答
0
投票

将分割中的部分放入文本框的一种方法是引用数组中的文本框,并从行中的项目数组中设置它们。

使用Math.Min,我们可以确定如果行上没有足够的项目,那么我们不会尝试将文本设置为不存在的内容。

Using openreader As StreamReader = New StreamReader(openFileDialog1.FileName)
    Dim tb = {TextBox1, TextBox2, TextBox3, TextBox4}

    Try
        While Not openreader.EndOfStream
            Dim currentline As String
            currentline = openreader.ReadLine()
            currentline = currentline.Trim(" "c)
            Dim inputparts() As String = currentline.Split(" "c)

            For i = 0 To Math.Min(tb.Length, inputparts.Length)
                tb(i).Text = inputparts(i)
            Next

        End While

    Catch ex As Exception
        MessageBox.Show("The file could not be read. The original error is: " & ex.Message)
    End Try

End Using

我使用了Using语句,因为它确保即使发生异常也会关闭文件。

如果在代码的最顶部添加Imports System.IO,则不必在System.IO.StreamReader之类的内容中输入qazxswpoi。

© www.soinside.com 2019 - 2024. All rights reserved.