简体   繁体   中英

C# DirectorySecurity SetOwner on subcontainers and objects

I am trying to change ownership of a windows folder and everything inside it. Basially I am trying to check the box that would be there if you did this manually in windows that says "Replace owner on subcontainers and objects". This will need to work over a network share path. I am able to get 1 folder deep but then it just stops there. This does not include the base folder changing either.

 foreach (string directory in Directory.GetDirectories(dirPath))
            {
                var di = new DirectoryInfo(directory);
                IdentityReference user = new NTAccount(Login.authUserName.ToString());
                DirectorySecurity dSecurity = di.GetAccessControl();
                dSecurity.SetOwner(user);
                di.SetAccessControl(dSecurity);
            }

You can use Directory.GetDirectories with SearchOption.AllDirectories in order to recurse.

But it seems easier to just get the DirectoryInfo di objects directly using DirectoryInfo.GetDirectories , which has the same and more recursive options.

IdentityReference user = new NTAccount(Login.authUserName.ToString());

var root = new DirectoryInfo(dirPath);
foreach (var di in root.GetDirectories("*", SearchOption.TopDirectoryOnly).Prepend(root))
{
    var dSecurity = di.GetAccessControl();
    dSecurity.SetOwner(user);
    di.SetAccessControl(dSecurity);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM