1

When copying a directory on the same volume (ex. c:) from one folder to another with the .NET DirectoryInfo.MoveTo, the access control are preserved: in other words the destination has the same security has the origin and does not inherit the one of it's new parent.

I would like to be able to move a folder and it's content but replacing the permissions like it was a copy of the folder.

Is there a simple way to achieve this in C#?

gigi
  • 796
  • 9
  • 21

1 Answers1

0
const string source = @"C:\test1\test";
const string target = @"C:\test2\test";
Directory.Move(source, target);

// Get Directory Info
var dInfo = new DirectoryInfo(target); // Or FileInfo
var dSec = dInfo.GetAccessControl();
// Set Security to inherit
dSec.SetAccessRuleProtection(false, false);

// Remove Rules/Accounts that are not inherited
var rules = dSec.GetAccessRules(true, false, typeof (NTAccount));
foreach (FileSystemAccessRule rule in rules)
    dSec.RemoveAccessRule(rule);

// Commit changes to folder
dInfo.SetAccessControl(dSec);

At first move the folder. Then create a DirectoryInfo and get the AccessControl. With SetAccessRuleProtection you can reset and inherit security from the parent. Then remove all accounts/user that are not inherited. The last line is to commit changes.

Files: I the folder contains files and other folders, it depends on their security settings. if they are set to inherit too then they inherit from the folder you changed with the code above (the parent folder) so if you are not sure what they might be set to you have to do that recursive with all sub-folder and also with all files...

The Code for the Files is the same, except the DirectoryInfo there you have to use FileInfo.

For further information visit File.Move does not inherit permissions from target directory? // Link for me, to read later: http://support.microsoft.com/kb/320246/de

Community
  • 1
  • 1
Steven Spyrka
  • 678
  • 7
  • 18
  • this will only work if the directory is empty. as stated in the question what I need is to copy a directory and it's content – gigi Aug 05 '13 at 12:14
  • Here you go... i edited the code above. I hope this helps you. If not you can contact me. – Steven Spyrka Aug 20 '13 at 12:54