Louis Rhys
Louis Rhys

Reputation: 35627

Copy file, overwrite if newer

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?

Upvotes: 26

Views: 37399

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use the FileInfo class and it's properties and methods:

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

Upvotes: 46

Joe Johnston
Joe Johnston

Reputation: 2936

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

Upvotes: 2

JMK
JMK

Reputation: 28059

In a batch file, this will work:

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

Upvotes: 0

ronen
ronen

Reputation: 1490

You can use the FileInfo class:

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

Upvotes: 11

Related Questions