好的,我想做的只是比较 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
两个字节数组是相同的,一个数组从资源中获取文件字节,另一个从计算机中获取字节。出于测试目的,我在两个数组中都使用了相同的文件,但根据提供的代码,我得到的只是 No。两者都具有相同的长度,我遍历了它们,它们在相同的点上都有相同的字节。那怎么了?我应该使用什么代码?请帮助我。
使用 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
如果您的目的是比较 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 个字符串。