我需要一个 VBA 例程来计算文件内容的 MD5 哈希值。我找到了一些例子(例如,here https://stackoverflow.com/questions/2826302/how-to-get-the-md5-hex-hash-for-a-file-using-vba)但我发现当文件名包含某些 Unicode 字符时它们会崩溃,所以我尝试调整代码以避免这种情况。
此代码不会导致错误,但也不会返回正确的 MD5 哈希值。怎么了?
Public Function FileToMD5Hex(sFileName As String) As String
Dim enc
Dim bytes
Dim outstr As String
Dim pos As Integer
Set enc = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
'Convert the string to a byte array and hash it
bytes = GetFileBytes(sFileName)
bytes = enc.ComputeHash_2((bytes))
'Convert the byte array to a hex string
For pos = 1 To LenB(bytes)
outstr = outstr & LCase(Right("0" & Hex(AscB(MidB(bytes, pos, 1))), 2))
Next
FileToMD5Hex = outstr
Set enc = Nothing
End Function
Private Function GetFileBytes(path As String) As Byte()
Dim fso As Object
Set fso = CreateObject("scripting.FileSystemObject")
Dim fil As Object
Set fil = fso.GetFile(path)
' Dim fpga As Variant
GetFileBytes = fil.OpenAsTextStream().Read(fil.Size)
Set fil = Nothing
Set fso = Nothing
End Function
有一些字符序列Scripting.FileSystemObject
无法正确处理TextStream
.
Use ADODB.Stream
ActiveX 从文件中检索字节数组。它可以完美地处理文本和二进制类型的数据,还允许更改字符串的字符集(FSO
仅适用于 ASCII 和 Unicode,并且仅适用于文件)。
Function GetFileBytes(strPath As String) As Byte()
With CreateObject("ADODB.Stream")
.Type = 1 ' adTypeBinary
.Open
.LoadFromFile (strPath)
GetFileBytes = .Read()
End With
End Function
另一种处理二进制数据的 ActiveX 是SAPI.spFileStream
。最重要的优点之一 - 它允许仅将文件的一部分加载到内存(在某些情况下,当比较大文件时,它可以帮助大幅提高性能,按块检查 md5)。
Function GetFileBytes(strPath As String) As Byte()
Dim arrContent As Variant
With CreateObject("SAPI.spFileStream")
.Open strPath, 0
.Read arrContent, CreateObject("Scripting.FileSystemObject").GetFile(strPath).Size
.Close
End With
GetFileBytes = arrContent
End Function
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)