大家下午好,我正在尝试对 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 和 paths2 传递给而不是执行 fileNames1 和 2 步骤,但是,对于我的一生,我在框架中找不到类似的东西。
干杯山 姆
使用 Path.GetFilename
方法而不是手动切路径字符串怎么样?
http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx