C# 使用system.IO c从A目录合并到B目录更新B目录
我想比较两个相等的目录A和B与子目录。如果我在A中更改、删除或包含目录或文件,我需要考虑B。是否有C例程可以做到这一点?我有这个习惯,但我不能继续。我只想更新我在A到B中更改的内容,而不是全部。如果我在a中删除了一个目录,但在B中没有删除该目录一旦您在每个目录中拥有完整的文件列表,您就可以使用页面上记录的FullOuterJoin代码。如果你让每一个的键都是DirA和DirB加上其他字符下的相对路径,那么你会得到一个很好的比较。这将产生三个数据集—A中的文件而不是B、B中的文件而不是A以及匹配的文件。然后,您可以迭代每个文件,并根据需要执行所需的文件操作。它看起来像这样:C# 使用system.IO c从A目录合并到B目录更新B目录,c#,system.io.directory,C#,System.io.directory,我想比较两个相等的目录A和B与子目录。如果我在A中更改、删除或包含目录或文件,我需要考虑B。是否有C例程可以做到这一点?我有这个习惯,但我不能继续。我只想更新我在A到B中更改的内容,而不是全部。如果我在a中删除了一个目录,但在B中没有删除该目录一旦您在每个目录中拥有完整的文件列表,您就可以使用页面上记录的FullOuterJoin代码。如果你让每一个的键都是DirA和DirB加上其他字符下的相对路径,那么你会得到一个很好的比较。这将产生三个数据集—A中的文件而不是B、B中的文件而不是A以及匹配的
public static IEnumerable<TResult> FullOuterJoin<TA, TB, TKey, TResult>(
this IEnumerable<TA> a,
IEnumerable<TB> b,
Func<TA, TKey> selectKeyA,
Func<TB, TKey> selectKeyB,
Func<TA, TB, TKey, TResult> projection,
TA defaultA = default(TA),
TB defaultB = default(TB),
IEqualityComparer<TKey> cmp = null)
{
cmp = cmp ?? EqualityComparer<TKey>.Default;
var alookup = a.ToLookup(selectKeyA, cmp);
var blookup = b.ToLookup(selectKeyB, cmp);
var keys = new HashSet<TKey>(alookup.Select(p => p.Key), cmp);
keys.UnionWith(blookup.Select(p => p.Key));
var join = from key in keys
from xa in alookup[key].DefaultIfEmpty(defaultA)
from xb in blookup[key].DefaultIfEmpty(defaultB)
select projection(xa, xb, key);
return join;
}
IEnumerable<System.IO.FileInfo> filesA = dirA.GetFiles(".", System.IO.SearchOption.AllDirectories);
IEnumerable<System.IO.FileInfo> filesB = dirB.GetFiles(".", System.IO.SearchOption.AllDirectories);
var files = filesA.FullOuterJoin(
filesB,
f => $"{f.FullName.Replace(dirA.FullName, string.Empty)}",
f => $"{f.FullName.Replace(dirB.FullName, string.Empty)}",
(fa, fb, n) => new {fa, fb, n}
);
var filesOnlyInA = files.Where(p => p.fb == null);
var filesOnlyInB = files.Where(p => p.fa == null);
// Define IsMatch - the filenames already match, but consider other things too
// In this example, I compare the filesizes, but you can define any comparison
Func<FileInfo, FileInfo, bool> IsMatch = (a,b) => a.Length == b.Length;
var matchingFiles = files.Where(p => p.fa != null && p.fb != null && IsMatch(p.fa, p.fb));
var diffFiles = files.Where(p => p.fa != null && p.fb != null && !IsMatch(p.fa, p.fb));
// Iterate and copy/delete as appropriate
//拍摄文件系统的快照。IEnumerable list1=dir1.GetFiles.,System.IO.SearchOption.AllDirectories;IEnumerable list2=dir2.GetFiles.,System.IO.SearchOption.AllDirectories;//使用递归复制每个子目录。source.GetDirectories中的foreach DirectoryInfo diSourceSubDir{DirectoryInfo nextargetsubdir=target.createsubdirectoriydisosourcesubdir.Name;CopyAlldiSourceSubDir,nextargetsubdir;}我只需要一个例子来更新目录B如果你想简单地添加到你的问题中,我无法在两个目录之间开发代码:在目录A中,我删除或重命名文件和目录,之后必须在B目录中反映此更改。我如何在它们之间建立此连接。我测试了你的代码,但我无法继续运行Michael Bray,但如上所述:我无法在两个目录之间开发代码,因为:在目录A中,我删除或重命名文件和目录,之后必须在B目录中反映此更改。我如何在它们之间建立此连接。我测试了你的代码,但无法继续