VB.NET流读取计算crc32

时间:2014-08-09 17:03:55

标签: vb.net streamwriter crc32

我正在使用带有缓冲区的流读取器和写入器来读取文件。是否有可能同时计算文件的crc32校验和,以便在每次迭代期间评估缓冲区,结果将是完整文件的crc32,而不是必须两次读取文件?这是代码:

   Public Function APPEND_FILE_TO_FILE(ByVal SOURCE_FILE As String, ByVal DESTINATION_FILE As String)
        Dim nn As New FileInfo(SOURCE_FILE)
        Dim BUFFER(BUFFER_SIZE) As Byte
        Dim BYTES_READ As Long = 0
        Using inFile As New System.IO.FileStream(SOURCE_FILE, IO.FileMode.Open, IO.FileAccess.Read)
            Using outFile As New System.IO.FileStream(DESTINATION_FILE, IO.FileMode.OpenOrCreate, IO.FileAccess.Write)
                Do
                    BYTES_READ = inFile.Read(BUFFER, 0, BUFFER_SIZE)
                    TOTAL_PROCESSED_DATA += BYTES_READ ' GUI related
                    outFile.Write(BUFFER, 0, BYTES_READ)
                Loop While BYTES_READ > 0
            End Using
        End Using
    End Function

CRC32功能:

Public Function GetCRC32(ByVal sFileName As String) As String
    Try
        Dim FS As FileStream = New FileStream(sFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
        Dim CRC32Result As Integer = &HFFFFFFFF
        Dim Buffer(4096) As Byte
        Dim ReadSize As Integer = 4096
        Dim Count As Integer = FS.Read(Buffer, 0, ReadSize)
        Dim CRC32Table(256) As Integer
        Dim DWPolynomial As Integer = &HEDB88320
        Dim DWCRC As Integer
        Dim i As Integer, j As Integer, n As Integer
        'Create CRC32 Table
        For i = 0 To 255
            DWCRC = i
            For j = 8 To 1 Step -1
                If (DWCRC And 1) Then
                    DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
                    DWCRC = DWCRC Xor DWPolynomial
                Else
                    DWCRC = ((DWCRC And &HFFFFFFFE) \ 2&) And &H7FFFFFFF
                End If
            Next j
            CRC32Table(i) = DWCRC
        Next i
        'Calcualting CRC32 Hash
        Do While (Count > 0)
            For i = 0 To Count - 1
                n = (CRC32Result And &HFF) Xor Buffer(i)
                CRC32Result = ((CRC32Result And &HFFFFFF00) \ &H100) And &HFFFFFF
                CRC32Result = CRC32Result Xor CRC32Table(n)
            Next i
            Count = FS.Read(Buffer, 0, ReadSize)
        Loop
        Return Hex(Not (CRC32Result))
    Catch ex As Exception
        Return ""
    End Try
End Function

0 个答案:

没有答案