Search code examples
c#directoryactive-directorynas

Getting local group from mapped drives c#


We are facing on issue with Giving folder access to mapped path from c#. We have one map drive and it's mapped using code. It's working fine, and we try to give the access using below code.

DirectorySecurity dirSec = Directory.GetAccessControl(clientFolder);
dirSec.AddAccessRule(new FileSystemAccessRule(@"Local group Name", FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));

Getting error while adding the AddAccessRule.

Error:

Some or all identity references could not be translated.

Trace:

 at System.Security.Principal.NTAccount.Translate(IdentityReferenceCollection sourceAccounts, Type targetType, Boolean forceSuccess)
   at System.Security.Principal.NTAccount.Translate(Type targetType)
   at System.Security.AccessControl.CommonObjectSecurity.ModifyAccess(AccessControlModification modification, AccessRule rule, Boolean& modified)
   at System.Security.AccessControl.CommonObjectSecurity.AddAccessRule(AccessRule rule)

Note: We are using AD service account to map the NAS and we are trying to add local group from parent computer. This group not accessible by AD and it's same domain.

Please give me any idea, give the access for Local service account to NAS.


Solution

  • We added the group manually to one folder and we are storing the IdentityReference.Value into one variable. Then we easily got the IdentityReference,Using this we added programmatic to other folders. Below code used to get the IdentityReference

            public IdentityReference getReference(string NameOfDirectory)
            {
                DirectorySecurity dirSec = Directory.GetAccessControl(NameOfDirectory);
                AuthorizationRuleCollection accessRules;
                IdentityReference identity = null;
                accessRules = dirSec.GetAccessRules(true, true, typeof(NTAccount));
                foreach (FileSystemAccessRule rule in accessRules)
                {
                    if (identity == null)
                    {
                        if (rule.IdentityReference.Value != null && rule.IdentityReference.Value.Equals(Constants.securityId))
                        {
                            dirSec.RemoveAccessRuleSpecific(rule);
                            identity = rule.IdentityReference;
                            break;
                        }
                    }
                }
                return identity;
            }