Search code examples
c#windowssecurityiofilesystems

Set Access Permissions for a Whole Group on a Directory


I am writing a C# application which needs to create a folder, and then give DOMAIN\Users full permissions. When I try to pass in Environment.UserDomainName + @"\Users" it throws a System.Security.Principal.IdentityNotMappedException. Currently, I have this code:

DirectoryInfo dirInfo = new DirectoryInfo(path);
DirectorySecurity dirSec = dirInfo.GetAccessControl();

// All users should have full control.
dirSec.AddAccessRule(new FileSystemAccessRule(Environment.UserDomainName + @"\Users", FileSystemRights.FullControl, AccessControlType.Allow));

dirInfo.SetAccessControl(dirSec);

How can I make this "work", as in allowing users full control of the directory which is stored in path?

This is the full exception:

Exception


Solution

  • I did some testing on my pc and found that when adding a domain user this worked:

    Environment.UserDomainName + @"\Users"
    

    For a local machine account, I had to do:

    @".\Users"
    

    Since you're testing on your home PC I'm assuming that you aren't on a domain and are trying to add the local machine Users group.