使用LINQ比较文件夹
本文关键字:文件夹 比较 LINQ 使用 | 更新日期: 2023-09-27 18:12:58
Edit:编辑更详细的问题:
我正在比较两个大文件夹,找出两个文件夹中哪些文件是共同的。MSDN有使用LINQ解决的程序:文章MSDN
然而,有一个问题,我正试图解决。
假设我有两个文件夹。文件夹a和文件夹b。文件夹a和文件夹B有两个子文件夹1和2。
- C: ' FolderA ' 1 '。aspx
- C: ' FolderA ' 2 ' b。aspx
- C: ' FolderB ' 1 ' a.aspx
- C: ' FolderB ' 1 ' b.aspx
。在FolderA和FolderB中,b.aspx和b.aspx是相同的。注意b.aspx存在于不同的子文件夹中。
当前结果:C: ' FolderA ' ' a.aspx 12 C: ' FolderA ' ' b.aspx
我期望结果匹配只是C:'FolderA'1'a。Aspx,因为它与文件夹结构匹配,而且文件是相同的。
我是否能够修改FileCompare类来执行位于同一目录结构中的文件的比较?
或
我应该做些什么改变来确保正确的比较。
谢谢!(Sanjeev
要做到这一点,您需要调整Equals()
函数的操作方式。我的建议如下:
步骤1 -使path
变量可用于Equals()
方法:
class CompareDirs
{
static void Main(string[] args)
{
// Create two identical or different temporary folders
// on a local drive and change these file paths.
string pathA = @"C:'TestDir";
string pathB = @"C:'TestDir2";
...
是
class CompareDirs
{
private string pathA, pathB;
static void Main(string[] args)
{
// Create two identical or different temporary folders
// on a local drive and change these file paths.
pathA = @"C:'TestDir";
pathB = @"C:'TestDir2";
...
步骤2 -更改Equals()
方法以考虑此信息:
我建议使用.replace(pathA, pathB)
来启用文件目录的比较,就好像路径是相同的一样。因此,在同一子目录结构中的任何文件将具有相同的总体目录(在执行替换操作之后)。
public bool Equals(System.IO.FileInfo f1, System.IO.FileInfo f2)
{
return (f1.Name == f2.Name &&
f1.Length == f2.Length &&
f1.DirectoryName.replace(pathA, pathB) == f2.DirectoryName.replace(pathA, pathB) );
}