3

こんにちは、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のような既存の配列メソッドがあり、fileNames1と2のステップを実行するのではなく、パス1とパス2を渡すことができましたが、私の人生では見つけることができませんでした.フレームワークでそれのようなもの。

乾杯、サム

4

1 に答える 1

1

Path.GetFilenameパス文字列を手動で切り刻む代わりに、メソッドを使用するのはどうですか?

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

于 2012-06-28T08:38:59.333 に答える