简体   繁体   English

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

[英]Copy file, overwrite if newer

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

You can use the FileInfo class and 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);
    }
}

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) ;
}

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 would copy but falls a little short on readability. 从技术上讲,为不存在的文件创建一个fileinfo将具有DateTime.Min的LastWriteTime,因此它复制但在可读性方面略有不足。 I hope this tested code helps someone. 我希望这个经过测试的代码有助

**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 if the 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);
    }
}

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM