[英]compare two folders for non identical files with SymmetricDifference?
[英]comparing two folders for non identical files?
var dir1Files = dir1.GetFiles("*", SearchOption.AllDirectories).Select(x => new { x.Name, x.Length });
var dir2Files = dir2.GetFiles("*", SearchOption.AllDirectories).Select(x => new { x.Name, x.Length });
var onlyIn1 = dir1Files.Except(dir2Files).Select(x => new { x.Name });
File.WriteAllLines(@"d:\log1.txt", foo1);
在這里,我正在根據名稱比較兩個文件並在文本文件中寫入...但是我需要將名稱與目錄名稱一起寫入...但是我無法選擇這樣的目錄名稱
var onlyIn1 = dir1Files.Except(dir2Files).Select(x => new { x.Name,x.DirectoryName });
有什么建議嗎?
使用FullName
是否可以解決您的問題?
var onlyIn1 = dir1Files.Except(dir2Files).Select(x => new { x.FullName });
或者,您可以在Select
語句中放一個自定義字符串:
// get strings in the format "file.ext, c:\path\to\file"
var onlyIn1 = dir1Files.Except(dir2Files).Select(x =>
string.Format("{0}, {1}", x.Name, x.Directory.FullName));
為了能夠在對象中使用此信息,請不要在第一步中創建信息有限的匿名類型,而應保留完整的FileInfo
對象:
var dir1Files = dir1.GetFiles("*", SearchOption.AllDirectories);
var dir2Files = dir2.GetFiles("*", SearchOption.AllDirectories);
更新
您的代碼示例中的真正問題是Except
將使用默認的相等比較器進行比較 。 對於大多數類型(當然,對於匿名類型),這意味着它將比較對象引用。 由於您有兩個包含FileInfo
對象的列表,因此Except
將返回第一個列表中的所有對象,而在第二個列表中找不到相同的對象實例 。 由於第一個列表中的對象實例都不存在於第二個列表中,因此將返回第一個列表中的所有對象。
為了解決此問題(並仍然有權訪問要存儲的數據),您將需要使用接受IEqualityComparer<T>
的Except
重載 。 首先,讓我們創建IEqualityComparer
:
class FileInfoComparer : IEqualityComparer<FileInfo>
{
public bool Equals(FileInfo x, FileInfo y)
{
// if x and y are the same instance, or both are null, they are equal
if (object.ReferenceEquals(x,y))
{
return true;
}
// if one is null, they are not equal
if (x==null || y == null)
{
return false;
}
// compare Length and Name
return x.Length == y.Length &&
x.Name.Equals(y.Name, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(FileInfo obj)
{
return obj.Name.GetHashCode() ^ obj.Length.GetHashCode();
}
}
現在,您可以使用該比較器比較目錄中的文件:
var dir1 = new DirectoryInfo(@"c:\temp\a");
var dir2 = new DirectoryInfo(@"c:\temp\b");
var dir1Files = dir1.GetFiles("*", SearchOption.AllDirectories);
var dir2Files = dir2.GetFiles("*", SearchOption.AllDirectories);
var onlyIn1 = dir1Files
.Except(dir2Files, new FileInfoComparer())
.Select(x => string.Format("{0}, {1}", x.Name, x.Directory.FullName));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.