1

古いファイルを置き換えることができるかどうかを知りたいのですが、ファイルが古い場合はコピーしたくありません。問題は、すべてのディレクトリ内のファイル数が異なる可能性があることです。

多くのメソッドを記述したくはありません。単純な LINQ クエリを 1 つだけ記述しますが、LINQ はかなり苦手です。

LINQ を使用して true または false を返したいと思います。

System.IO.FileInfo[] filesSource = new System.IO.DirectoryInfo(sources).GetFiles();  
System.IO.FileInfo[] filesTarget = new System.IO.DirectoryInfo(target).GetFiles();  

bool canCopy = ... 
    /* group - if file have the same name
       if can't match and group - simply ignore it */ ...
(x => x.Source.LastWriteTime < x.Target.LastWriteTime).Count() == 0;
4

4 に答える 4

1

これは私が思いつくことができる最高のものです

リンクウェイ:

System.IO.FileInfo[] filesSource = new System.IO.DirectoryInfo(source).GetFiles();
            System.IO.FileInfo[] filesTarget = new System.IO.DirectoryInfo(dest).GetFiles();

bool canCopy = !(from fileInfo in filesSource 
                 let tmp = filesTarget.FirstOrDefault(f => f.Name == fileInfo.Name) 
                 where tmp != null && tmp.LastWriteTime > fileInfo.LastWriteTime 
                 select fileInfo).Any();

通常の方法:

private static bool CanCopyAllFiles(string source, string dest)
{
    System.IO.FileInfo[] filesSource = new System.IO.DirectoryInfo(source).GetFiles();
    System.IO.FileInfo[] filesTarget = new System.IO.DirectoryInfo(dest).GetFiles();

    foreach (FileInfo fileInfo in filesSource)
    {
        FileInfo tmp = filesTarget.FirstOrDefault(f => f.Name == fileInfo.Name);
        if (tmp != null && tmp.LastWriteTime > fileInfo.LastWriteTime)
        {
            return false;
        }
    }
    return true;
}
于 2013-04-17T17:09:27.703 に答える
1

したがって、最初に行う必要があるのは、2 つのファイルのコレクションを結合することです。各ソース ファイルをその宛先ファイル (存在する場合) と一致させる必要があります。これは、GroupJoin(一致する宛先アイテムのないアイテムを返す必要があるため、通常の結合とは対照的に) で行われます。

結合が完了すると、宛先ファイルがあり、かつ宛先ファイルがより新しいアイテムを除外できます。

public static IEnumerable<FileInfo> FilesToCopy(DirectoryInfo source, DirectoryInfo target)
{
    return from sourceFile in source.GetFiles()
            join targetFile in target.GetFiles()
            on sourceFile.FullName equals targetFile.FullName
            into destinationFiles
            let targetFile = destinationFiles.FirstOrDefault()
            where !destinationFiles.Any() ||
                sourceFile.LastWriteTime > targetFile.LastWriteTime
            select sourceFile;
}
于 2013-04-17T17:20:50.643 に答える