Taking ownership of files with 'broken' permissions

后端 未结 2 1435
太阳男子
太阳男子 2020-12-06 02:14

I\'m trying to overcome the following situation.

Given a directory stored on an NTFS volume, where:

  1. The directory owner is set to someone else (a non-p
相关标签:
2条回答
  • 2020-12-06 03:05

    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

    0 讨论(0)
  • 2020-12-06 03:14

    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.

    0 讨论(0)
提交回复
热议问题