Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file, overwrite if newer

Tags:

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?

like image 713
Louis Rhys Avatar asked Dec 27 '12 09:12

Louis Rhys


People also ask

Does copy overwrite files?

By default, cp will overwrite files without asking. If the destination file name already exists, its data is destroyed. If you want to be prompted for confirmation before files are overwritten, use the -i (interactive) option.

How do I copy files without overwriting?

If you are copying files using drag-drop or copy/paste, you may simply choose “Skip this file” or “Skip these files” option to not overwrite the files that are already existed at the destination folder. Or, if you are using command line copy, you can answer N to bypass these files that are already existed.

Does Copy command overwrite?

Usually, when you run a cp command, it overwrites the destination file(s) or directory as shown. To run cp in interactive mode so that it prompts you before overwriting an existing file or directory, use the -i flag as shown.

How do I overwrite a file?

Overwriting a File, Part 1 To edit the settings for a file, locate the file you wish to overwrite and hover over the file name. Click the chevron button that appears to the right of the file name and select Overwrite File from the menu.


1 Answers

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);     } } 
like image 168
Tim Schmelter Avatar answered Oct 21 '22 07:10

Tim Schmelter