Add user account to user-group regardless the O.S language

395 views Asked by At

In the function below, in this line I use the language-specific name "Users":

GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Users");

How I can do it language-specific aware?.

I mean that for example, in my language, Spanish, the group name is "Usuarios", so the function will throw an exception because the english name is not found.

I would liketo be able to add the user to Administrador, standard users, and guests, without worrying about the machine current culture language. Is it possibly?.


The function:

public static bool CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires)
{

    try
    {
        PrincipalContext context = new PrincipalContext(ContextType.Machine);
        UserPrincipal user = new UserPrincipal(context);
        user.SetPassword(password);
        user.DisplayName = displayName;
        user.Name = username;
        user.Description = description;
        user.UserCannotChangePassword = canChangePwd;
        user.PasswordNeverExpires = pwdExpires;
        user.Save();


        //now add user to "Users" group so it displays in Control Panel
        GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Users");
        group.Members.Add(user);
        group.Save();

        return true;
    }
    catch (Exception ex)
    {
        LogMessageToFile("error msg" + ex.Message);
        return false;
    }

}
1

There are 1 answers

0
Martin Liversage On BEST ANSWER

You can use a well-known SID to specify the group you want to retrieve. For the Users group the SID is S-1-5-32-545 but by using the WellKnownSidType enum you can avoid putting the actual SID into your code:

var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
var principal = GroupPrincipal.FindByIdentity(context, IdentityType.Sid, sid.Value);