我正在开发一个C#应用程序.
我需要更改文件夹上的ACL,为此,我以提升的管理员身份运行程序,并且一切正常.
问题是,如果拥有该文件夹的用户被从系统中删除,那么当我尝试获取该文件夹的所有权时,会得到未授权的异常.
这是失败的代码:
using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
var directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
Directory.SetAccessControl(directoryInfo.FullName, directorySecurity);
}
异常发生在以下行:directoryInfo.GetAccessControl();
PrivilegeEnabler是Process Privileges中定义的类,用于获取文件的所有权.
解决方法:
我找到了解决方案.
您需要通过创建新的访问控制(无需调用GetAccessControl)并将所有者设置为当前进程来设置所有者.
然后您就可以对文件进行任何操作.
using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
//create empty directory security
var directorySecurity = new DirectorySecurity();
//set the directory owner to current user
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
//set the access control
Directory.SetAccessControl(directoryInfo.FullName, directorySecurity);
}