.Net库在保留时间戳的同时移动/复制文件

bul*_*ous 12 .net c# time file-io robocopy

有没有人知道.Net库,可以在不更改任何时间戳的情况下复制/粘贴或移动文件.我正在寻找的功能包含在一个名为robocopy.exe的程序中,但我想要这个功能,而不必共享该二进制文件.

思考?

Roy*_*ode 20

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;
}
Run Code Online (Sandbox Code Playgroud)


The*_*der 13

在没有管理权限的情况下执行时,Roy的答案将在尝试覆盖现有的只读文件或尝试在复制的只读文件上设置时间戳时抛出异常(UnauthorizedAccessException).

以下解决方案基于Roy的答案,但将其扩展为覆盖只读文件并更改复制的只读文件的时间戳,同时保留文件的只读属性,同时仍然执行而没有管理员权限.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)