我需要用另一個目錄中的備份文件替換一個目錄中的所有文件。必須保留所有文件屬性/權限/所有權。 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。
謝謝你讓我朝着正確的方向前進。 – MDave