1

I'm writing a code to group equal files in a given directory using the hashCompute method. I have done most of the work but I can't seem to group my files. I want files with same hash value to be grouped together.

Here's a sample of my code:

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.");
    }
}
ekad
  • 14,436
  • 26
  • 44
  • 46
  • i'm thinking i can use linq..but please where do i insert the code and how ..i'm very new to linq..or is there another simple way – Anthony Ogbechie Oct 29 '12 at 19:00
  • What do you mean by "grouping" the files? What is the output you're trying to get? – Jon B Oct 29 '12 at 19:24
  • i want to output eqaul files in groups...example if there are 10 files in my folder and there are 2 groups of the same file..i want those same files outputted then a space and then the next group of equal files – Anthony Ogbechie Oct 29 '12 at 19:29

1 Answers1

3

You could do something like this:

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);
}
itsme86
  • 19,266
  • 4
  • 41
  • 57
  • @TorbjörnKalin I agree. The OP just seemed confused by the LINQ portion, so wanted to get that part out there without obscuring it. – itsme86 Oct 29 '12 at 19:30