Taking ownership of files with 'broken' permissions

拟墨画扇 提交于 2019-11-27 22:26:02

I had the same problem and just posting here for anybody else who may come here searching like me:

You need to explicitly enable SeTakeOwnershipPrivilege in code. I found Process Privileges to be really helpful dealing with this sort of thing.

Here is how it fixed my code (seems like for some reason even though i have the privilege, the process doesn't unless i explicitly enable it):

using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
    directoryInfo = new DirectoryInfo(path);
    directorySecurity = directoryInfo.GetAccessControl();

    directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
    Directory.SetAccessControl(path, directorySecurity);    
}

PS: Thanks Simon.. your answer gave me a place to start from.

You need to take ownership before you add access.

using (var user = WindowsIdentity.GetCurrent())
{
    var ownerSecurity = new FileSecurity();
    ownerSecurity.SetOwner(user.User);
    File.SetAccessControl("c:\\path\\to\\broken", ownerSecurity);

    var accessSecurity = new FileSecurity();
    accessSecurity.AddAccessRule(new FileSystemAccessRule(user.User, FileSystemRights.FullControl, AccessControlType.Allow));
    File.SetAccessControl("c:\\path\\to\\broken", accessSecurity);
}

Also if you are setting DirectorySecurity you will need this

using (var user = WindowsIdentity.GetCurrent())
{
    var ownerSecurity = new DirectorySecurity();
    ownerSecurity.SetOwner(user.User);
    Directory.SetAccessControl("c:\\path\\to\\broken", ownerSecurity);

    var accessSecurity = new DirectorySecurity();
    accessSecurity.AddAccessRule(new FileSystemAccessRule(user.User, FileSystemRights.FullControl, AccessControlType.Allow));
    Directory.SetAccessControl("c:\\path\\to\\broken", accessSecurity);
}

If that doesn't work try this

http://blog.mikeobrien.net/2009/11/taking-ownership-and-setting-admin.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!