读/写二进制文件溢出

时间:2012-02-24 03:14:21

标签: vb.net

我想要一些代码的帮助。这是我的代码:

    Public Function ReadBinaryFileLarge(strFilename As String) As Byte()
    Dim position As Integer = 0
    Dim bufferSize As Integer = 4096
    Dim bytes() As Byte

    Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open)
        ReDim bytes((fsOpen.Length) - 1)
        Do
            If (position + bufferSize) > fsOpen.Length Then
                fsOpen.Read(bytes, position, fsOpen.Length - position)
                Exit Do
            Else
                fsOpen.Read(bytes, position, bufferSize)
            End If

            position += bufferSize

            Application.DoEvents()
        Loop
    End Using

    Return bytes

End Function

Public Sub SaveBinaryFileLarge(strFilename As String, bytesToWrite() As Byte)
    Dim position As Integer = 0

    Using fsNew As FileStream = New FileStream(strFilename, FileMode.Create, FileAccess.Write)
        Do
            Dim intToCopy As Integer = Math.Min(4096, bytesToWrite.Length - position)
            Dim buffer(intToCopy - 1) As Byte
            Array.Copy(bytesToWrite, position, buffer, 0, intToCopy)
            fsNew.Write(buffer, 0, buffer.Length)

            position += intToCopy

            Application.DoEvents()

        Loop While position < bytesToWrite.Length

    End Using

End Sub

我的问题是,对于大文件,字节数组不能声明为大。我需要将它加载到一个字节数组中,以对字节数组进行一些加密工作。我正在玩这个代码:

    Public Function ReadBinaryFileTest(strFilename As String) As Byte()()
    Const SIZE As Integer = &H1000 '4096 <-experiment with this value
    Dim bytes()() As Byte

    Using fsOpen As FileStream = New FileStream(strFilename, FileMode.Open, FileAccess.Read, FileShare.Read, SIZE)
        Dim ubound = (fsOpen.Length / SIZE) - 1
        bytes = new byte(ubound)()
        Dim read As Integer = 0

        For index As Integer = 0 To ubound
            bytes(index) = New Byte(SIZE - 1)
            read = fsOpen.Read(bytes(index), 0, SIZE)
            If read <> SIZE Then
                Array.Resize(bytes(index), read) 'this should only happen once if at all
            End If
        Next
    End Using

    Return bytes

End Function

但是我收到了这些错误:

  

bytes = new byte(ubound)()

'{'期待

  

bytes(index)=新字节(SIZE - 1)

类型'字节'没有构造函数。

这是解决此问题的正确方法吗?如果没有,我该怎么攻击呢?

1 个答案:

答案 0 :(得分:0)

你必须使用ReDim,

ReDim bytes(ubound-1)

或者

 bytes = New Byte(ubound)() {}