简体   繁体   中英

Set Owner of Directory and Sub Containers in C#

When setting the owner of a preexisting folder in Server 2008 R2, is there a way to make this propagate to all of the sub containers under the object? You can do this in the Properties diag, but I do not see a switch for this.

I am looking for a way to avoid recusing through the sub containers to do this.

This code will switch the owner for only the top level directory.

DirectoryInfo myDirectoryInfo = new DirectoryInfo("PATH HERE");
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();

System.Security.Principal.IdentityReference myOwner = 
    new System.Security.Principal.NTAccount("TARGET OWNER ACCOUNT");
myDirectorySecurity.SetOwner(myOwner);

myDirectoryInfo.SetAccessControl(myDirectorySecurity);

There is no overload that will provide this for you.

But the following code will do that:

DirectoryInfo directoryInfo = new DirectoryInfo(path);
var directories = directoryInfo.EnumerateDirectories("*.*", SearchOption.AllDirectories);
foreach (var directory in directories)
{
    // set owner                
}

Note that I use EnumerateDirectories instead of Directory.GetDirectories , it will return instantly even if there are 1000's of directories.

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