Create Directory and give user FullControl problem
I am having a problem creating a directory with specific permissions.
//Make sure Tools directory exists
DirectoryInfo oMyDirectoryInfo = new DirectoryInfo(oInstance.szToolsPath);
if (!oMyDirectoryInfo.Exists)
{
oMyDirectoryInfo.Create();
DirectorySecurity oDirectorySecurity = oMyDirectoryInfo.GetAccessControl();
oDirectorySecurity.AddAccessRule(new FileSystemAccessRule((Settings.Default.LoginDomain + "\\" + Settings.Default.LoginUsername), FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
oMyDirectoryInfo.SetAccessControl(oDirectorySecurity);
}
Now this creates the directory and I can see that the Login has been added to the security tab. However when I Impersonate the Login and try and copy files to that directory I get a Unauthorized Exception. I can create a file (no data), I can create a folde开发者_JAVA技巧r but I cannot write data to files (but I set FullControl :/)
I dug further in to the permissions through Windows and I see that it applies to subfolders but I would like to set this to files too. How do I do this through code?
This is on Windows 7
When you are creating your FileSystemAccessRule
, you are specifying InheritanceFlags.ContainerInherit
. This propagates the mask to child containers. If you want to apply to leaf objects (files in your case), you need to specify InheritanceFlags.ObjectInherit
, or for both,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
Use this to add access rule
string adminUserName = Environment.UserName;
DirectorySecurity dirService = Directory.GetAccessControl(directory + hexID);
FileSystemAccessRule fsa = new FileSystemAccessRule(adminUserName,FileSystemRights.FullControl, AccessControlType.Deny);
dirService.AddAccessRule(fsa);//add
Directory.SetAccessControl(directory + hexID, dirService);
and use this to remove access rule
string adminUserName = Environment.UserName;
DirectorySecurity dirService = Directory.GetAccessControl(directory + hexID);
FileSystemAccessRule fsa = new FileSystemAccessRule(adminUserName, FileSystemRights.FullControl, AccessControlType.Deny);
dirService.RemoveAccessRule(fsa);//remove
Directory.SetAccessControl(directory + hexID, dirService);
精彩评论