Search code examples
c#administratorsystem-administration

Get Guest built-in account name in C#


I want to get Guest built-in account name with C#. Because language is different on different regions and Guest is only for English version of Windows and for example, on Spanish Windows, Guest is Invitado. What I want to do is get the name and edit the account with that name I get, Like setting password or add some groups to it.

I already tried this code:

            var sGuest = new SecurityIdentifier(WellKnownSidType.AccountGuestSid, null);
            PrincipalContext systemContext = null;
            systemContext = new PrincipalContext(ContextType.Machine);
            guestPrincipal = UserPrincipal.FindByIdentity(systemContext, IdentityType.Name, sGuest.ToString());

And I get this error:

System.ArgumentNullException: 'The domainSid parameter must be specified for creating well-known SID of type AccountGuestSid.

Solution

  • The SID of the local guest account takes the form S-1-5-21domain-501, where domain is the SID of the machine. Because the domain SID is required to construct the guest account SID, the constructor to SecurityIdentifier fails if the domainSid parameter is null. You can get the machine SID via WMI and pass that as the domainSid argument to the SecurityIdentifier constructor.

    Alternatively, it is possible to obtain the guest account without the machine SID. One method for doing so is to use a PrincipalSearcher to identify the user account whose SID is that of the well known guest account SID, and query its Name property to get the local name of the account:

    // using System.Security.Principal;
    // using System.DirectoryServices.AccountManagement;
    new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Machine)))
                    .FindAll()
                    .Single(a => a.Sid.IsWellKnown(WellKnownSidType.AccountGuestSid))
                    .Name // returns the local account name, e.g., 'Guest'