C#相交部分匹配

时间:2012-06-28 08:28:22

标签: c# arrays compare intersect

下午好, 我正在尝试对2个文件夹的内容进行比较,我让它在时尚之后工作,但我很好奇是否有更好的方法。这就是我所拥有的:

    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("--");
    }

感觉我错过了一个技巧,并且有一个现有的数组方法,比如Intersect,我可以通过paths1&amp; paths2而不是fileNames1&amp; 2步,但是,对于我的生活,我在框架中找不到类似的东西。

干杯, 萨姆

1 个答案:

答案 0 :(得分:1)

如何使用Path.GetFilename方法而不是手动切断路径字符串?

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