2012-04-26 67 views
-1

终于修复我的最后一个问题后,我与结束的代码是VB.NET对于每个

Function MD5(ByVal strToHash As String) As String 
    Dim md5Obj As New Security.Cryptography.MD5CryptoServiceProvider 
    Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash) 

    bytesToHash = md5Obj.ComputeHash(bytesToHash) 

    Dim strResult As String = "" 

    For Each b As Byte In bytesToHash 
     strResult += b.ToString("x2") 
    Next 

    Return strResult 
End Function 



Dim words As IEnumerable(Of String) = File.ReadLines(OpenFileDialog1.FileName) 
    For Each word As String In words 
     If String.Equals(MD5(word), hash.Text) Then 
      Label2.Text = word 
     Else : Label2.Text = "Hash Could Not Be Cracked" 
     End If 
    Next 

现在我需要使其停止一次哈希的话,我键入的散列相匹配!

回答

0

你可以使用LINQ的FirstOrDefault,由于您使用的ReadLines代替ReadAllLines反正:

Dim firstWord = (From line In IO.File.ReadLines(OpenFileDialog1.FileName) 
    Where String.Equals(MD5(line), hash.Text)).FirstOrDefault() 
If firstWord IsNot Nothing Then 
    Label2.Text = firstWord 
Else 
    Label2.Text = "Hash Could Not Be Cracked" 
End If 

另一种方式是一个简单的循环:

Dim lines = IO.File.ReadAllLines(OpenFileDialog1.FileName) 
Dim matchingLine As String = Nothing 
For i = 0 To lines.Length -1 
    Dim line = lines(i) 
    If String.Equals(MD5(line), hash.Text)) Then 
     matchingLine = line 
     Exit For 
    End If 
Next 
If matchingLine IsNot Nothing Then 
    Label2.Text = matchingLine 
Else 
    Label2.Text = "Hash Could Not Be Cracked" 
End If 
+0

它没有工作=/ – user1328301 2012-04-26 18:48:54

+0

@ user1328301:我刚编辑我的答案,看看。 – 2012-04-26 18:50:25

+0

它需要在for循环中,因为它们打开的文件有多行。 – user1328301 2012-04-26 18:53:47

0

要停止循环,可使用Exit For

Dim words As IEnumerable(Of String) = File.ReadLines(OpenFileDialog1.FileName) 

For Each word As String In words 
    If MD5(word) = hash.Text Then 
     Label2.Text = word 
     Exit For 
    Else : Label2.Text = "Hash Could Not Be Cracked" 
    End If 
Next 

但请注意,Else在这里没有任何意义(表单将不会被更新,直到该方法被留下)并且String.Equals可以在这里被=(我已经这样做)替换。