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);
}
CodePudding user response:
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);
}