-2

I've created in C# a program which creates a directory and some files inside it.

How can I set (programmatically - if possible) the Full-Control right only for Administrator? The ideal case would be to inhibit the Write and Read rights for a non-administrator user (creating a "kind of hidden folder"), but it would also be enough for me to set only the Read right for a non-administrator user, stop.

I've tried to search in Stack Overflow, but nobody has written about the same problem. Inf act, everybody talks about "all users". Me no.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
rlnnclt
  • 23
  • 7
  • 1
    https://stackoverflow.com/questions/8944765/c-sharp-set-directory-permissions-for-all-users-in-windows-7 – CodeCaster Nov 25 '21 at 14:07
  • 1
    @CodeCaster **out of place**. The question is different. – rlnnclt Nov 25 '21 at 14:08
  • 1
    What do you mean by "out of place"? But alright, let me rephrase: please read [ask] and show what you have tried. Searching the web for "C# set directory access control permissions" yields plenty of results. Perhaps no single example will match your exact requirements, but I assume you're able to replace something like `WellKnownSidType.BuiltinUsersSid` with `WellKnownSidType.BuiltinAdministratorsSid`? – CodeCaster Nov 25 '21 at 14:10

1 Answers1

1

Yup, it's possible. First, you have to create the directory then set it's access rules.

var directory = Directory.CreateDirectory("SomeFolder");

var directorySecurity = directory.GetAccessControl();

var administratorRule = new FileSystemAccessRule("Administrators", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
var usersRole = new FileSystemAccessRule("Users", FileSystemRights.CreateDirectories | FileSystemRights.CreateFiles, AccessControlType.Allow);

directorySecurity.AddAccessRule(administratorRule);
directorySecurity.AddAccessRule(usersRole);

directory.SetAccessControl(directorySecurity);
cemahseri
  • 397
  • 2
  • 12