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)
归档时间: |
|
查看次数: |
6006 次 |
最近记录: |