Folder Permissions - Some or all identity references could not be translated

I would like to set folder ACL on remote server for a domain user but get always following error message:

Some or all identity references could not be translated

What am I doing wrong?

This is my code:

string folderPath = @"\\remoteServer\testDirectory"     
string accountName = "domainUser"
string domainName = "mydomain";
accountName = domainName + "\\" + accountName;
//What rights are we setting?

//set on dir itself
FileSystemAccessRule accessRule = new FileSystemAccessRule(accountName, FileSystemRights.FullControl, AccessControlType.Allow);

DirectoryInfo dInfo = new DirectoryInfo(folderPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
//dInfo.SetAccessControl(dSecurity);

dSecurity.AddAccessRule(accessRule);`

If I enter only userName instead of domainname\username permission will be set but with "unknown account"

Could someone please help...

Thanks in advance.


I found solution for this Problem. SecurityIdentifier Object created with SID of user you want to permit must be created. See my solution code:

FileSystemRights Rights;
            
string folderPath = @"\\remoteServer.domainname\testDirectory";
            
// Get User from AD with System.DirectoryServices.AccountManagement;
UserPrincipal user = GetPrinicpalBySamAccountName("userSamAccount"); 
string usersid = user.Sid.ToString();           

// What rights are we setting?
SecurityIdentifier secIdentifierSid = new SecurityIdentifier(usersid);
            
// Set on dir itself
FileSystemAccessRule accessRule = new FileSystemAccessRule(usersid, FileSystemRights.FullControl, AccessControlType.Allow);
            
DirectoryInfo dInfo = new DirectoryInfo(folderPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
            
dSecurity.AddAccessRule(accessRule);
dInfo.SetAccessControl(dSecurity);

https://social.msdn.microsoft.com/Forums/de-DE/682e88c0-e044-46f9-8b5d-55f185e85a1a/directory-acl-berechtigung?forum=visualcsharpde&prof=required


Improving HeonAle's answer:

GetPrincipalBySamAccountName() method isn't defined in .NET.

So, we need a way to get the Principal, which has the SID.

For a user:

                // set up domain context
                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

                // find a user
                UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "UserName");
                string sid = user.Sid.ToString();

For a group:

                PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
                GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "GroupName");
                string sid = group.Sid.ToString();

Then, the rest is the same:

SecurityIdentifier secIdentifierSid = new SecurityIdentifier ( sid );  
FileSystemAccessRule AccessRule = new FileSystemAccessRule ( secIdentifierSid , FileSystemRights.FullControl, AccessControlType.Allow );