使用StreamReader

时间:2017-08-07 21:54:32

标签: vb.net

我遇到了问题,我有一个正在处理的程序,我必须能够一个接一个地读取多个.txt文件来更新名为words()的字符串数组。主要问题是我上传的第一个文件进入files()字符串数组,当我运行拖放事件时,数组已满,不允许我上传第二个。如何在成功上传后重置files()数组。

示例代码:

Dim words(7) As String
Dim i As Integer = 0
 Public Sub frmMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop

    Dim word As String = ""
    Try
        Dim files() As String = e.Data.GetData(DataFormats.FileDrop)

        For Each path In files

            MsgBox(path)
            Dim sr As New StreamReader(path)

            Do Until sr.Peek = -1
                word = sr.ReadLine()

                words(i) = word

                frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " + words(i))
                i = i + 1

            Loop


        Next
        GetPower()
    Catch ex As Exception

        'MessageBox.Show(ex.ToString())

    End Try

End Sub
Private Sub frmMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter

    If e.Data.GetDataPresent(DataFormats.FileDrop) Then

        e.Effect = DragDropEffects.Copy

    End If


End Sub

1 个答案:

答案 0 :(得分:2)

我相信这是因为你没有重置i,这意味着我最终会增加你的words()数组的范围,这个数组只有7号,顺便说一下如果其中一个文件也会引发错误有超过7行。

    For Each path In files
          i = 0 'reset counter

          MsgBox(path)
          Dim sr As New StreamReader(path)

          Do Until sr.Peek = -1
              word = sr.ReadLine()

              words(i) = word

              frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " +     words(i))
              i = i + 1

          Loop

      Next