哈希集中的 C# MD5 哈希

C# MD5 hashing in hashset

我对 C# 比较陌生。我目前正在学习 hashset 并了解 hashset 不允许 hashset 内有相同的元素。我的问题是我能否使用 md5 散列对目录中的文件进行散列并将它们存储在散列集中,以便我可以以某种方式检查重复的散列或文件?

HashSet<T> Class 是独特元素的集合。 HashSet class 的命名空间是 System.Collections.Generic。它是在 .NET 3.5.

中引入的

让我们以文件为例:

static void Main(string[] args)
{
    HashSet<string> FileData = new HashSet<string>();
    using (var md5 = MD5.Create())
    {
         using (var stream = File.OpenRead("C:\FolderTest\Document.txt"))
         {
              var hash = md5.ComputeHash(stream);
              var data = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
              FileData.Add(data);
         }
         using (var stream = File.OpenRead("C:\FolderTest\Document.txt"))
         {
              var hash = md5.ComputeHash(stream);
              var data = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
              FileData.Add(data);
         }
         using (var stream = File.OpenRead("C:\FolderTest\Document2.txt"))
         {
              var hash = md5.ComputeHash(stream);
              var data = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
              FileData.Add(data);
         }
    }
    foreach (var file in FileData)
    {
         Console.WriteLine(file);
    } 
    Console.ReadKey();
}

在上面的代码中,我们创建了一个简单的 HashSet<string> 类型的 HashSet 并将字符串添加到其中。 如上所述,即使我们尝试添加重复的哈希数据字符串,我们也不会得到任何错误,但是当我们迭代集合时,我们找不到字符串。

How you compare the results afterward is up to you; you can convert the byte array to base64 for example, or compare the bytes directly. (Just be aware that arrays don't override Equals. Using base64 is simpler to get right, but slightly less efficient if you're really only interested in comparing the hashes.) see these answers

HashSet的特点:

  • 当我们添加元素时HashSet<T>自动增加 HashSet的容量。
  • 它用于我们想要防止重复的情况 正在插入集合中。
  • HashSet提供了很多数学集合操作,比如set 加法(联合)和集合减法。