簡體   English   中英

讀/寫二進制文件溢出

[英]Read/Write binary files overflow

我需要一些代碼方面的幫助。 這是我的代碼:

    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

但是我得到這些錯誤:

字節=新字節(ubound)()

預期為“ {”

位元組(索引)=新位元組(SIZE-1)

類型“字節”沒有構造函數。

這是解決此問題的正確方法嗎? 如果沒有,我應該怎么攻擊呢?

您必須使用ReDim,

ReDim bytes(ubound-1)

要么

 bytes = New Byte(ubound)() {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM