在C#中获得Guest内置帐户名

问题描述 投票:0回答:1

我想使用C#获取Guest内置帐户名。由于不同地区的语言不同,并且Guest仅用于Windows的英语版本,例如,在西班牙语Windows中,Guest是Invitado。我想要做的就是获取名称,然后使用获得的名称来编辑帐户,例如设置密码或向其中添加一些组。

我已经尝试过此代码:

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

我收到此错误:

System.ArgumentNullException: 'The domainSid parameter must be specified for creating well-known SID of type AccountGuestSid.
c# administrator system-administration
1个回答
2
投票

本地访客帐户的SID的格式为S-1-5-21domain-501,其中domain是计算机的SID。因为需要域SID来构造来宾帐户SID,所以如果SecurityIdentifier参数为null,则domainSid的构造函数将失败。您可以通过WMI获取计算机SID,并将其作为domainSid参数传递给SecurityIdentifier构造函数。

或者,可以在没有计算机SID的情况下获得访客帐户。这样做的一种方法是使用PrincipalSearcher来识别SID为众所周知的来宾帐户SID的用户帐户,并查询其Name属性以获取帐户的本地名称:

// 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'
© www.soinside.com 2019 - 2024. All rights reserved.