We can find an Active Directory User’s GUID and SID in C# by using the UserPrincipal class which exists under the namespace
System.DirectoryServices.AccountManagement and it is available only from .NET 3.5.
System.DirectoryServices.AccountManagement and it is available only from .NET 3.5.
Step 1 : Create a new Console Application project in Visual Studio.
Step 2 : Add a a.NET reference System.DirectoryServices.AccountManagement
Step 3 : Then use the below C# code to find an AD user’s DisplayName, GUID, SID and UserPrincipalName.
using System; using System.DirectoryServices.AccountManagement; namespace GetADUserInfo { class Program { static void Main(string[] args) { // Set up domain context PrincipalContext ctx = new PrincipalContext(ContextType.Domain); // Find user UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "<Username>"); if (user != null) { Console.WriteLine("Name: " + user.DisplayName); Console.WriteLine("GUID: " + user.Guid); Console.WriteLine(" SID: " + user.Sid); Console.WriteLine("UPN: " + user.UserPrincipalName); } } } }
Advertisement