如何在VB中将数据从文件复制到数组

时间:2013-12-27 12:03:15

标签: vb.net

我正在粘贴代码..我能够读取文件,但是无法放入数组,我得到了运行时错误。我已经使行粗体,我得到错误。任何人帮助我,我很VB的新手。

Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices
Imports System.IO
Imports System.IO.Compression

    Public Class Form1

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim openFileDialog1 As OpenFileDialog = New OpenFileDialog

            ' Set filter options and filter index.
    openFileDialog1.Filter = "BMP Files (*.bmp)|*.bmp|All Files (*.*)|*.*"
    openFileDialog1.FilterIndex = 1

    openFileDialog1.Multiselect = True

            ' Call the ShowDialog method to show the dialogbox.
    Dim UserClickedOK As Boolean = openFileDialog1.ShowDialog
    PictureBox1.Image = Image.FromFile(openFileDialog1.FileName)
    Dim data() As Byte = File.ReadAllBytes(openFileDialog1.FileName)

        ' Dim hexval As String
          '  Dim objStreamWriter As StreamWriter
     Dim buff(data.Length()) As String
     Dim counter As Integer
     Dim Arr() As String = Nothing

        ' the file path and the file name to the StreamWriter constructor.
        ' objStreamWriter = New StreamWriter("C:\users \karmic\My Documents\Text.txt")

            'Write a line of text.
     For i = LBound(data) To UBound(data)
     **Arr(i) = Hex(data(i))**                       -runtime error

      If i = data.Length() - 1 Then

      Continue For
      End If
      If (Hex(data(i))) = (Hex(data(i + 1))) Then
      counter = counter + 1
      ' MsgBox(counter)
      Continue For
      Else
                'objStreamWriter.Write(hexval)
                'MsgBox(hexval)

                ' Array.Copy(hexval, Arr(i), data.Length)
                'objStreamWriter.Write(", ")
                'objStreamWriter.Write(Hex(counter + 1))
      MsgBox(Hex(counter + 1))
                'objStreamWriter.Write(", ")


     End If
              'MsgBox(Array.Length())
     Next
     End Sub
     End Class

1 个答案:

答案 0 :(得分:0)

您的Arr()似乎是一个动态数组,因为在声明数组时没有包含数组的上限。每次要使用ReDim语句更改数组的上限时,都需要重新声明动态数组。

ReDim Preserve Arr(i) = Hex(data(i))

每次使用ReDim时,所有动态数组元素中的值都将被删除。因此,在这种情况下,每次重新声明数组以保留元素的值时,都必须指定Preserve语句。希望这会有所帮助。