Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net library to move / copy a file while preserving timestamps

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?

like image 672
bulltorious Avatar asked Aug 23 '11 17:08

bulltorious


3 Answers

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;
}
like image 159
Roy Goode Avatar answered Nov 15 '22 13:11

Roy Goode


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;
    }
}
like image 33
The Lonely Coder Avatar answered Nov 15 '22 15:11

The Lonely Coder


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

  • CreationTime
  • LastAccessTime
  • LastWriteTime
like image 41
Daniel Hilgarth Avatar answered Nov 15 '22 15:11

Daniel Hilgarth