I want an application to create a folder and restrict users other than current and admins from accessing it. As a result of the code below though current user loses access as well and cannot delete the folder.
string rootPath = Environment.GetEnvironmentVariable("TEMP");
var rootDirectory = new DirectoryInfo(rootPath);
DirectoryInfo subFolder = rootDirectory.CreateSubdirectory("SubFolder");
var directorySecurity = subFolder.GetAccessControl();
var adminitrators = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
directorySecurity.AddAccessRule(
new FileSystemAccessRule(
adminitrators,
FileSystemRights.FullControl,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow));
directorySecurity.AddAccessRule(
new FileSystemAccessRule(
WindowsIdentity.GetCurrent().Name,
FileSystemRights.FullControl,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow));
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
directorySecurity.AddAccessRule(
new FileSystemAccessRule(
everyone,
FileSystemRights.FullControl,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Deny));
subFolder.SetAccessControl(directorySecurity);
subFolder.Delete(true); // <-- System.UnauthorizedAccessException