2013-10-01 71 views
0

我需要用另一個目錄中的備份文件替換一個目錄中的所有文件。必須保留所有文件屬性/權限/所有權。 File.Copy就像Windows資源管理器一樣複製文件,清除所有權限並將所有者更改爲自己。如何複製文件並保留所有權?

我發現了,就這樣還要保持其原有權限的例子,但並不: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得到這個異常。如果我將枚舉更改爲AccessControlSections.Access,代碼將起作用,但只保留權限,而不是所有權。我是本地管理員,甚至當目的地是我的本地PC時,它也不起作用。我以管理員身份運行Visual Studio 2010。

回答

0

我沒有權限調用GetAccessControl上,這不是我的本地機器上的任何文件(第一個錯誤),我想不出我設置擁有的任何文件的擁有者(第二個錯誤)我只能授予「取得所有權」的權利。作爲域管理員運行該工具解決了所有問題。

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); 
} 
+0

謝謝你讓我朝着正確的方向前進。 – MDave

相關問題