1

我正在编写代码以使用该hashCompute方法对给定目录中的相同文件进行分组。我已经完成了大部分工作,但我似乎无法对我的文件进行分组。我希望将具有相同哈希值的文件组合在一起。

这是我的代码示例:

public static void myhashedfiles()
{
    string directory;
    Console.WriteLine("please enter a folder name:");
    directory = (Console.ReadLine());

    if (directory.Length < 1)
    {
        Console.WriteLine("enter a directory or folder name!");
        return;
    }

    DirectoryInfo dir = new DirectoryInfo(directory);
    try
    {
        FileInfo[] files = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

        HashAlgorithm hash = HashAlgorithm.Create();

        byte[] hashValue;

        foreach (FileInfo fInfo in files)
        {
            FileStream fileStream = fInfo.Open(FileMode.Open);
            fileStream.Position = 0;

            hashValue = hash.ComputeHash(fileStream);

            PrintByteArray(hashValue);
            Console.WriteLine(fInfo.Name);

            fileStream.Close();
        }
    }
    catch (DirectoryNotFoundException)
    {
        Console.WriteLine("Error: The directory specified could not be found.");
    }
    catch (IOException)
    {
        Console.WriteLine("Error: A file in the directory could not be accessed.");
    }
}
4

1 回答 1

3

你可以这样做:

var groups = files
    .Select(file => new {
        fInfo = file,
        Hash = hash.ComputeHash(file.Open(FileMode.Open)) }
    ).GroupBy(item => item.Hash);

foreach (var grouping in groups)
{
    Console.WriteLine("Files with hash value: {0}", grouping.Key);
    foreach(var item in grouping)
        Console.WriteLine(item.fInfo);
}
于 2012-10-29T19:25:22.250 回答