3

Good Afternoon all, I'm trying to run a comparison of the contents of 2 folders and I have it working after-a-fashion but I'm curious whether there's a better way. Here's what I have:

    static void Main(string[] args)
    {
        reportDiffs("C:\\similar\\a", "C:\\similar\\b");
        Console.WriteLine("--\nPress any key to quit");
        Console.ReadKey();
    }

    public static void reportDiffs(string sourcePath1, string sourcePath2)
    {
        string[] paths1 = Directory.GetFiles(sourcePath1);
        string[] paths2 = Directory.GetFiles(sourcePath2);
        string[] fileNames1 = getFileNames(paths1, sourcePath1);
        string[] fileNames2 = getFileNames(paths2, sourcePath2);
        IEnumerable<string> notIn2 = fileNames1.Except(fileNames2);
        IEnumerable<string> notIn1 = fileNames2.Except(fileNames1);
        IEnumerable<string> inBoth = fileNames1.Intersect(fileNames2);

        printOut("Files not in folder1: ", sourcePath2, notIn1);
        printOut("Files not in folder2: ", sourcePath1, notIn2);
        printOut("Files found in both: ", "", inBoth);
    }

    private static string[] getFileNames(string[] currentFiles, string currentPath)
    {
        string[] currentNames = new string[currentFiles.Length];
        int i;

        for (i = 0; i < currentNames.Length; i++)
        {
            currentNames[i] = currentFiles[i].Substring(currentPath.Length);
        }
        return currentNames;
    }

    private static void printOut(string headline, string currentPath, IEnumerable<string> fileNames)
    {
        Console.WriteLine(headline);
        foreach (var n in fileNames)
        {
            Console.WriteLine(currentPath + n);
        }
        Console.WriteLine("--");
    }

It feels like I'm missing a trick and that there's an existing array method, like Intersect, that I could have passed paths1 & paths2 to rather than doing the fileNames1 & 2 step but, for the life of me, I couldn't find anything like it in the framework.

Cheers, Sam

Sam2S
  • 165
  • 1
  • 6

1 Answers1

1

How about using the Path.GetFilename method instead of chopping the path strings manually?

http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx

Hinek
  • 9,519
  • 12
  • 52
  • 74
  • 1
    OH nifty, should've known there'd be something like that available. Was so busy looking for partial intersects it didn't even occur to me. Swapped that out & it works a charm. – Sam2S Jun 28 '12 at 12:15