【发布时间】:2015-03-03 14:30:47
【问题描述】:
我需要知道两个文件是否相同。起初我比较了文件大小和创建时间戳,但这还不够可靠。我想出了以下代码,这似乎可行,但我希望有人有更好、更简单或更快的方法。
基本上我正在做的是将文件内容流式传输到字节数组,并通过 System.Security.Cryptography 比较他们的 MD5 哈希。
在此之前我会进行一些简单的检查,因为如果两个文件路径相同或其中一个文件不存在,则没有理由通读文件。
Public Function CompareFiles(ByVal file1FullPath As String, ByVal file2FullPath As String) As Boolean
If Not File.Exists(file1FullPath) Or Not File.Exists(file2FullPath) Then
'One or both of the files does not exist.
Return False
End If
If String.Compare(file1FullPath, file2FullPath, True) = 0 Then
' fileFullPath1 and fileFullPath2 points to the same file...
Return True
End If
Dim MD5Crypto As New MD5CryptoServiceProvider()
Dim textEncoding As New System.Text.ASCIIEncoding()
Dim fileBytes1() As Byte, fileBytes2() As Byte
Dim fileContents1, fileContents2 As String
Dim streamReader As StreamReader = Nothing
Dim fileStream As FileStream = Nothing
Dim isIdentical As Boolean = False
Try
' Read file 1 to byte array.
fileStream = New FileStream(file1FullPath, FileMode.Open)
streamReader = New StreamReader(fileStream)
fileBytes1 = textEncoding.GetBytes(streamReader.ReadToEnd)
fileContents1 = textEncoding.GetString(MD5Crypto.ComputeHash(fileBytes1))
streamReader.Close()
fileStream.Close()
' Read file 2 to byte array.
fileStream = New FileStream(file2FullPath, FileMode.Open)
streamReader = New StreamReader(fileStream)
fileBytes2 = textEncoding.GetBytes(streamReader.ReadToEnd)
fileContents2 = textEncoding.GetString(MD5Crypto.ComputeHash(fileBytes2))
streamReader.Close()
fileStream.Close()
' Compare byte array and return result.
isIdentical = fileContents1 = fileContents2
Catch ex As Exception
isIdentical = False
Finally
If Not streamReader Is Nothing Then streamReader.Close()
If Not fileStream Is Nothing Then fileStream.Close()
fileBytes1 = Nothing
fileBytes2 = Nothing
End Try
Return isIdentical
End Function
【问题讨论】:
-
在问题中发布任何非html/javascript/css代码时,请勿使用带有
<>符号的页面图标,请使用{}按钮。 -
这似乎是一种很好的做事方式。我会将您的方法拆分为具有特定功能的较小方法,例如 GetFileMD5()。您是在寻求意见还是有具体问题?
-
现在我已经实际查看了代码,您可以稍微缩短代码,但使用 StreamReader 对象上的
Using语句。此外,如果您只是想根据数据内容了解文件是否重复,您可以跳过文本编码并仅比较流的 MD5。另一件事,StreamReaders通常用于读取文本文件,如果这些文件有可能是其他文件类型,您应该考虑使用FileStream对象 -
抱歉用 而不是 {},菜鸟错误 :-) 但是感谢 cmets,非常有帮助!
标签: vb.net comparison filestream