Get the Current User’s Active Directory GUID and SID in C#

You can get an Active Directory User’s GUID and SID in C# by using UserPrincipal class. The UserPrincipal class exists under the namespace System.DirectoryServices.AccountManagement and it is available only from .NET 3.5.

# 1 – Create a new Console Application project in Visual Studio.

# 2 – Add a a.NET reference System.DirectoryServices.AccountManagement

# 3 – Then use the below code to get currently logged in user’s Name, GUID, SID and UserPrincipalName.

using System;
using System.DirectoryServices.AccountManagement;
 
namespace ADUserInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Name: " + UserPrincipal.Current.Name);
            Console.WriteLine("GUID: " + UserPrincipal.Current.Guid);
            Console.WriteLine(" SID: " + UserPrincipal.Current.Sid);
            Console.WriteLine("UPN: " + UserPrincipal.Current.UserPrincipalName);
        }
    }
}

Advertisement