Vb.net – How do i compare byte arrays in vb.net

arraysbytearraycompareequalsvb.net

Ok all i want to do is compare 2 byte arrays in vb.net . I tried these codes:

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

And

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

Both byte arrays are the same, one array takes byte from a file from resources and the other from the computer. For testing purposes, I used the same file in both arrays but all I get is No according to the code provided. Both have the same lengths, i looped through both of them, both have same bytes at same points. Then what's wrong? What code should I use? Please help me.

Best Answer

Use 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)

Compare two small files

    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