Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Intersecting Partial Matches

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

like image 274
Sam2S Avatar asked Sep 10 '26 01:09

Sam2S


1 Answers

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

like image 97
Hinek Avatar answered Sep 11 '26 16:09

Hinek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!