我如何比较vb.net中的字节数组

时间:2013-10-17 22:58:36

标签: arrays vb.net compare bytearray equals

好的我想做的就是比较vb.net中的2字节数组。我试过这些代码:

If Byte.ReferenceEquals(bytearrayone, bytearraytwo) Then
  MsgBox("Yes", MsgBoxStyle.Information)
Else
  MsgBox("No", MsgBoxStyle.Critical)
End If

If Array.ReferenceEquals(bytearrayone, bytearraytwo) Then
  MsgBox("Yes", MsgBoxStyle.Information)
Else
  MsgBox("No", MsgBoxStyle.Critical)
End If

两个字节数组都相同,一个数组从资源中获取一个字节的字节,另一个数组从计算机获取。出于测试目的,我在两个阵列中使用了相同的文件,但根据提供的代码,我得到的只是否。两者都有相同的长度,我通过它们两个循环,在相同的点都有相同的字节。那有什么不对?我应该使用什么代码?请帮帮我。

2 个答案:

答案 0 :(得分:5)

使用SequenceEqual

    Dim foo() As Byte = {1, 2, 3, 4}
    Dim barT() As Byte = {1, 2, 3, 4}
    Dim barF() As Byte = {1, 2, 3, 5}

    Dim fooEqbarT As Boolean = foo.SequenceEqual(barT)
    Dim fooEqbarF As Boolean = foo.SequenceEqual(barF)

    Debug.WriteLine(fooEqbarT)
    Debug.WriteLine(fooEqbarF)

比较两个小文件

    Dim path1 As String = "pathnameoffirstfile"
    Dim path2 As String = "pathnameofsecondfile"

    Dim foo() As Byte = IO.File.ReadAllBytes(path1)
    Dim bar() As Byte = IO.File.ReadAllBytes(path2)

    If foo.SequenceEqual(bar) Then
        'identical
    Else
        'different
    End If

答案 1 :(得分:1)

如果您的目的是比较2个文件以查看内容是否相同,而不考虑有关文件的信息(即修改日期,名称,类型等),您应该在这两个文件上使用哈希。这是我用了一段时间的一些代码。有很多方法可以做到这一点。

''' <summary>
''' Method to get a unique string to idenify the contents of a file.
''' Works on any type of file but may be slow on files 1 GB or more and large files across the network.
''' </summary>
''' <param name="FI">System.IO.FileInfo for the file you want to process</param>
''' <returns>String around 50 characters long (exact length varies)</returns>
''' <remarks>A change in even 1 byte of the file will cause the string to vary 
''' drastically so you cannot use this to see how much it differs by.</remarks>
Public Shared Function GetContentHash(ByVal FI As System.IO.FileInfo) As String
    Dim SHA As New System.Security.Cryptography.SHA512Managed()
    Dim sBuilder As System.Text.StringBuilder
    Dim data As Byte()
    Dim i As Integer
    Using fs As New IO.FileStream(FI.FullName, IO.FileMode.Open)
        data = SHA.ComputeHash(fs)
        fs.Flush()
        fs.Close()
    End Using
    sBuilder = New System.Text.StringBuilder
    ' Loop through each byte of the hashed data 
    ' and format each one as a hexadecimal string.
    For i = 0 To data.Length - 1
        sBuilder.Append(data(i).ToString("x2"))
    Next i
    Return sBuilder.ToString()
End Function

您需要在每个文件上运行此命令,以获得唯一标识文件的字符串,然后比较2个字符串。