14

Does anyone know of a .Net library where a file can be copied / pasted or moved without changing any of the timestamps. The functionality I am looking for is contained in a program called robocopy.exe, but I would like this functionality without having to share that binary.

Thoughts?

bulltorious
  • 7,649
  • 3
  • 46
  • 73

4 Answers4

22
public static void CopyFileExactly(string copyFromPath, string copyToPath)
{
    var origin = new FileInfo(copyFromPath);

    origin.CopyTo(copyToPath, true);

    var destination = new FileInfo(copyToPath);
    destination.CreationTime = origin.CreationTime;
    destination.LastWriteTime = origin.LastWriteTime;
    destination.LastAccessTime = origin.LastAccessTime;
}
Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
Roy Goode
  • 2,862
  • 18
  • 22
14

When executing without administrative privileges Roy's answer will throw an exception (UnauthorizedAccessException) when attempting to overwrite existing read only files or when attempting to set the timestamps on copied read only files.

The following solution is based on Roy's answer but extends it to overwrite read only files and to change the timestamps on copied read only files while preserving the read only attribute of the file all while still executing without admin privilege.

public static void CopyFileExactly(string copyFromPath, string copyToPath)
{
    if (File.Exists(copyToPath))
    {
        var target = new FileInfo(copyToPath);
        if (target.IsReadOnly)
            target.IsReadOnly = false;
    }

    var origin = new FileInfo(copyFromPath);
    origin.CopyTo(copyToPath, true);

    var destination = new FileInfo(copyToPath);
    if (destination.IsReadOnly)
    {
        destination.IsReadOnly = false;
        destination.CreationTime = origin.CreationTime;
        destination.LastWriteTime = origin.LastWriteTime;
        destination.LastAccessTime = origin.LastAccessTime;
        destination.IsReadOnly = true;
    }
    else
    {
        destination.CreationTime = origin.CreationTime;
        destination.LastWriteTime = origin.LastWriteTime;
        destination.LastAccessTime = origin.LastAccessTime;
    }
}
Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
The Lonely Coder
  • 557
  • 8
  • 12
4

You can read and write all the timestamps there are, using the FileInfo class:

Daniel Hilgarth
  • 159,901
  • 39
  • 297
  • 411
2

You should be able to read the values you need, make whatever changes you wish and then restore the previous values by using the properties of FileInfo.

Paul Ruane
  • 34,423
  • 11
  • 60
  • 77