C# 复制文件,如果更新则覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14052661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:33:11  来源:igfitidea点击:

Copy file, overwrite if newer

c#.net

提问by Louis Rhys

In C#.NET, How to copy a file to another location, overwriting the existing file if the source file is newer than the existing file (have a later "Modified date"), and doing noting if the source file is older?

在 C#.NET 中,如何将文件复制到另一个位置,如果源文件比现有文件新(具有较晚的“修改日期”),则覆盖现有文件,并注意源文件是否较旧?

采纳答案by Tim Schmelter

You can use the FileInfoclassand it's properties and methods:

您可以使用FileInfo该类及其属性和方法:

FileInfo file = new FileInfo(path);
string destDir = @"C:\SomeDirectory";
FileInfo destFile = new FileInfo(Path.Combine(destDir, file.Name));
if (destFile.Exists)
{
    if (file.LastWriteTime > destFile.LastWriteTime)
    { 
        // now you can safely overwrite it
        file.CopyTo(destFile.FullName, true);
    }
}

回答by ronen

You can use the FileInfo class:

您可以使用 FileInfo 类:

FileInfo infoOld = new FileInfo("C:\old.txt");
FileInfo infoNew = new FileInfo("C:\new.txt");

if (infoNew.LastWriteTime > infoOld.LastWriteTime)
{
    File.Copy(source path,destination path, true) ;
}

回答by JMK

In a batch file, this will work:

在批处理文件中,这将起作用:

XCopy "c:\my directory\source.ext" "c:\my other directory\dest.ext" /d

回答by Joe Johnston

Here is my take on the answer: Copies not moves folder contents. If the target does not exist the code is clearer to read. Technically, creating a fileinfo for a non existent file will have a LastWriteTime of DateTime.Min so it wouldcopy but falls a little short on readability. I hope this tested code helps someone.

这是我对答案的看法:复制不移动文件夹内容。如果目标不存在,则代码更易于阅读。从技术上讲,为不存在的文件创建文件信息将具有 DateTime.Min 的 LastWriteTime,因此它可以复制但在可读性上有点不足。我希望这个经过测试的代码可以帮助某人。

**EDIT: I have updated my source to be much more flexable. Because it was based on this thread I have posted the update here. When using masks subdirs are not created ifthe subfolder does not contain matched files. Certainly a more robust error handler is in your future. :)

**编辑:我已经更新了我的源代码,使其更加灵活。因为它是基于这个线程,所以我在这里发布了更新。使用掩码时,如果子文件夹不包含匹配的文件,则不会创建子目录。当然,更强大的错误处理程序会在您的未来出现。:)

public void CopyFolderContents(string sourceFolder, string destinationFolder)
{
    CopyFolderContents(sourceFolder, destinationFolder, "*.*", false, false);
}

public void CopyFolderContents(string sourceFolder, string destinationFolder, string mask)
{
    CopyFolderContents(sourceFolder, destinationFolder, mask, false, false);
}

public void CopyFolderContents(string sourceFolder, string destinationFolder, string mask, Boolean createFolders, Boolean recurseFolders)
{
    try
    {
        if (!sourceFolder.EndsWith(@"\")){ sourceFolder += @"\"; }
        if (!destinationFolder.EndsWith(@"\")){ destinationFolder += @"\"; }

        var exDir = sourceFolder;
        var dir = new DirectoryInfo(exDir);
        SearchOption so = (recurseFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

        foreach (string sourceFile in Directory.GetFiles(dir.ToString(), mask, so))
        {
            FileInfo srcFile = new FileInfo(sourceFile);
            string srcFileName = srcFile.Name;

            // Create a destination that matches the source structure
            FileInfo destFile = new FileInfo(destinationFolder + srcFile.FullName.Replace(sourceFolder, ""));

            if (!Directory.Exists(destFile.DirectoryName ) && createFolders)
            {
                Directory.CreateDirectory(destFile.DirectoryName);
            }

            if (srcFile.LastWriteTime > destFile.LastWriteTime || !destFile.Exists)
            {
                File.Copy(srcFile.FullName, destFile.FullName, true);
            }
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
    }
}