Taking ownership of files with 'broken' permissions

后端 未结 2 1434
太阳男子
太阳男子 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

提交回复
热议问题