我试图在VB.NET 2010中创建一个具有简单功能的程序。
它必须将存储在文本文件中的数千个MD5哈希值与当前文件MD5哈希值进行比较,该程序在打开文件时自动计算。
像一个防病毒扫描程序。
实际上我的程序使用ReadAllText
系统将文本文件中的所有哈希值添加到文本框中,然后进行比较。
当Md5数据库(带有哈希的文本文件)很小但是当文件变大时,我的程序只是在打开后冻结,所以我决定使用ReadLine
而不是ReadAllText
。< / p>
现在我不能再使用文本框,所以请告诉我如何比较它们。 我尝试了一种方法,但它似乎不起作用。
以下是使用ReadLine
的代码。
问题出现在If Read contains(buff.tostring)
上
如果textbox.text包含(buff.toString)
这是代码
Try
TextBox2.Text = e.FullPath
ListBox3.Items.Add(TextBox2.Text.ToString)
Me.OpenFileDialog1.FileName = ""
Dim reader As StreamReader = New StreamReader("def.txt")
Dim read = reader.ReadLine()
Dim md5 As New MD5CryptoServiceProvider
Dim f As New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
f = New FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
f.Close()
If read.Contains(buff.ToString) Then
Me.OpenFileDialog1.FileName = e.FullPath
Form2.ShowDialog()
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.ClearProjectError()
End Try
答案 0 :(得分:1)
我首先会创建功能来分割功能。之后理解代码要容易得多。 将哈希存储在列表中,然后可以缓存此列表。
Try
TextBox2.Text = e.FullPath
ListBox3.Items.Add(TextBox2.Text.ToString)
Me.OpenFileDialog1.FileName = ""
Dim allHash As List(Of String) = GetAllHash()
Dim curHash As String = GetFileHash(e.FullPath)
If allHash.Contains(curHash) Then
Me.OpenFileDialog1.FileName = e.FullPath
Form2.ShowDialog()
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.ClearProjectError()
End Try
Function GetAllHash() As List(Of String)
' Store the data in a list instead
Return System.IO.File.ReadAllLines("def.txt").ToList()
End Function
Function GetFileHash(ByVal filename As String) As String
Dim md5 As New MD5CryptoServiceProvider
' Only open the file once
Dim f As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, &H2000)
md5.ComputeHash(f)
Dim hash As Byte() = md5.Hash
Dim buff As New StringBuilder
For Each hashByte As Byte In hash
buff.Append(String.Format("{0:X2}", hashByte))
Next
f.Close()
Return buff.ToString()
End Function