大家下午好
我正在尝试对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),我本可以将path1和path2传递给而不是执行fileNames1和2步骤,但是,对于我来说,我一生都找不到框架中的任何类似内容。
干杯,
山姆
最佳答案
如何使用Path.GetFilename
方法而不是手动剪切路径字符串?
http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx