To copy a file along with its metadata such as creation date, modification date, and file attributes, you need more than just a standard file copy. Most basic
File.Copy or shutil.copy calls do not preserve everything by default.
Below are solutions for copying file content + metadata across different platforms.
C# (.NET)
Full Copy (including timestamps and attributes)
using System;
using System.IO;
public static void CopyFileWithMetadata(string sourcePath, string destinationPath)
{
// Copy the file content and metadata
File.Copy(sourcePath, destinationPath, overwrite: true);
// Copy timestamps
File.SetCreationTime(destinationPath, File.GetCreationTime(sourcePath));
File.SetLastWriteTime(destinationPath, File.GetLastWriteTime(sourcePath));
File.SetLastAccessTime(destinationPath, File.GetLastAccessTime(sourcePath));
// Copy file attributes (e.g., ReadOnly, Hidden)
File.SetAttributes(destinationPath, File.GetAttributes(sourcePath));
}
File.Copy() copies the file content.
File.Set*Time() replicates creation and modification timestamps.
File.SetAttributes() copies attributes like ReadOnly,
Hidden, etc.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To copy a file along with its metadata such as creation date, modification date, and file attributes, you need more than just a standard file copy. Most basic
File.Copyorshutil.copycalls do not preserve everything by default.Below are solutions for copying file content + metadata across different platforms.
C# (.NET)
Full Copy (including timestamps and attributes)
File.Copy()copies the file content.File.Set*Time()replicates creation and modification timestamps.File.SetAttributes()copies attributes likeReadOnly,Hidden, etc.Python
Use
shutil.copy2()to copy file + metadatacopy2()copies the content and metadata (timestamps, mode).copy2will preserve modification and access times. Creation time is preserved on Windows.ctime) often cannot be set or preserved directly, as it's managed by the file system.Linux/macOS (Command Line)
Use
cp -porrsync-ppreserves mode, ownership, and timestamps.Or use
rsync:-a(archive mode) copies content with all metadata preserved.Windows (Command Line)
Use
robocopyto preserve metadata/COPYALLincludes timestamps, ACLs, owner info, attributes.Summary
shutil.copy2cp -p,rsync -arobocopy /COPYALL