簡體   English   中英

獲取C#中的Guest內置賬戶名

[英]Get Guest built-in account name in C#

我想用 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.

本地訪客帳戶的 SID 采用S-1-5-21domain-501形式,其中domain是機器的 SID。 因為域 SID 是構造來賓帳戶 SID 所必需的,所以如果domainSid參數是 null, SecurityIdentifier的構造函數將失敗。 您可以通過 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM