Search code examples
c#.netwindowsfile-permissions

Give specific local Windows user group read access to a folder and its subfolders


I want to programmatically give the local user group <MachineName>\IIS_IUSRS access to a folder and its subfolders.

My current code is looking like this:

DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();

var groupName = Environment.MachineName + @"\IIS_IUSRS";

directorySecurity.AddAccessRule(
    new FileSystemAccessRule(groupName,
    FileSystemRights.Read,
    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
    PropagationFlags.None,
    AccessControlType.Allow));

directoryInfo.SetAccessControl(directorySecurity);

But this is throwing a System.Security.Principal.IdentityNotMappedException. Replacing groupName with the SID for new SecurityIdentifier(WellKnownSidType.WorldSid, null); is working.

Do I need to get a SecurityIdenfier for a group and if yes how do I do that? Or do I need to do it completely different for groups?

Edit: BUILTIN\IIS_IUSRS didn't work either as I'm using Windows with German locale.


Solution

  • You don't need to use the SID, I wrote a program for work once which used "DOMAIN\GroupName" and it worked fine. Instead of:

    var groupName = Environment.MachineName + @"\IIS_IUSRS";
    

    Try:

    var groupName = @".\IIS_IUSRS";