Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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

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

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top