【发布时间】:2014-11-19 04:06:43
【问题描述】:
我想在 Visual Basic 中为文件夹中的所有文件生成单个 SHA256 哈希。我尝试了以下代码,但它会生成文件夹内所有文件的单独哈希,但不会生成单个哈希。有人可以帮忙吗?
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim directory As String
If TextBox2.Text.Length < 1 Then
Dim fdb As New FolderBrowserDialog
Dim dr As DialogResult = fdb.ShowDialog()
If (dr = DialogResult.OK) Then
directory = fdb.SelectedPath
Else
MsgBox("No directory selected")
Return
End If
Else
directory = TextBox2.Text
End If
Try
' Create a DirectoryInfo object representing the specified directory.
Dim dir As New DirectoryInfo(directory)
' Get the FileInfo objects for every file in the directory.
Dim files As FileInfo() = dir.GetFiles()
' Initialize a SHA256 hash object.
Dim mySHA256 As SHA256 = SHA256Managed.Create()
Dim hashValue() As Byte
' Compute and print the hash values for each file in directory.
Dim fInfo As FileInfo
For Each fInfo In files
' Create a fileStream for the file.
Dim fileStream As FileStream = fInfo.Open(FileMode.Open)
' Be sure it's positioned to the beginning of the stream.
fileStream.Position = 0
' Compute the hash of the fileStream.
hashValue = mySHA256.ComputeHash(fileStream)
' Write the name of the file to the Console.
MsgBox(fInfo.Name + ": ")
' Write the hash value to the Console.
PrintByteArray(hashValue)
' Close the file.
fileStream.Close()
Next fInfo
Return
Catch DExc As DirectoryNotFoundException
MsgBox("Error: The directory specified could not be found.")
Catch IOExc As IOException
MsgBox("Error: A file in the directory could not be accessed.")
End Try
End Sub
Public Function PrintByteArray(ByVal array() As Byte)
Dim i As Integer
For i = 0 To array.Length - 1
Label3.Text = (String.Format("{0:X2}", array(i)))
If i Mod 4 = 3 Then
Label3.Text = (" ")
End If
Next i
Return Label3.Text
End Function 'PrintByteArray
【问题讨论】:
-
看看这个以获得灵感(C#,但如果你只知道 VB 来制定一个方法,应该可以理解)stackoverflow.com/questions/3625658/creating-hash-for-folder/…。或者,最简单的方法是容器化(如果这是一个词 - 即将它们粘贴在容器文件中,如 tarball 或未压缩的 zip)然后散列容器
-
也不要将问题标记为生成错误,如果它实际上不是错误只是没有做你想要的(我假设你从某个地方复制了代码):)