如何复制文件并保留所有权?

时间:2013-10-01 20:58:27

标签: c# copy file-permissions file-copying

我需要将一个目录中的所有文件替换为另一个目录中的备份文件。必须保留所有文件属性/权限/所有权。 File.Copy,就像Windows资源管理器一样,复制文件,清除所有权限,并将所有者更改为自己。

我在SO上找到了一个示例,它应该保留其原始权限但不保留:Copy a file with its original permissions

代码:

File.Copy(originFile, destinationFile);
FileInfo originFileInfo = new FileInfo(originFile);
FileInfo destinationFileInfo = new FileInfo(destinationFile);
FileSecurity ac1 = originFileInfo.GetAccessControl(AccessControlSections.All);
ac1.SetAccessRuleProtection(true, true);
destinationFileInfo.SetAccessControl(ac1);

我收到了PrivilegeNotHeldException:

The process does not possess the 'SeSecurityPrivilege' privilege which is required for this operation.

如果我禁用UAC,我会收到此错误:

The security identifier is not allowed to be the owner of this object.

我使用AccessControlSections.All和AccessControlSections.Owner获得此异常。如果我将enum更改为AccessControlSections.Access,但代码仍然有效,但只保留权限,而不是所有权。我是本地管理员,即使目的地是我的本地PC,它也不起作用。我以管理员身份运行Visual Studio 2010。

2 个答案:

答案 0 :(得分:0)

您可能需要明确获取' SeSecurityPrivilege'。也许最简单的方法是使用Process Privileges

// Untested code, but it might look like this...
// (Add exception handling as necessary)
Process process = Process.GetCurrentProcess();

using (new PrivilegeEnabler(process, Privilege.Security))
{
    // Privilege is enabled within the using block.
    File.Copy(originFile, destinationFile);
    FileInfo originFileInfo = new FileInfo(originFile);
    FileInfo destinationFileInfo = new FileInfo(destinationFile);
    FileSecurity ac1 = originFileInfo.GetAccessControl(AccessControlSections.All);
    ac1.SetAccessRuleProtection(true, true);
    destinationFileInfo.SetAccessControl(ac1);
}

答案 1 :(得分:0)

我没有权限在我本地计算机上没有的任何文件上调用GetAccessControl(第一个错误),我无法设置我拥有的任何文件的所有者(第二个错误),我只能授予“取得所有权”权利。作为域管理员运行该工具解决了所有问题。

相关问题