Sinaesthetic
Sinaesthetic

Reputation: 12192

How do I find a user in Active Directory using their nativeguid in .net?

I'm running into a problem where running a DirectorySearcher isn't always returning a result successfully. For instance, I'll send in my manager's GUID using the following method to convert the string (NativeGuid):

public static string Guid2OctetString(string objectGuid)
{
    System.Guid guid = new Guid(objectGuid);
    byte[] byteGuid = guid.ToByteArray();
    string queryGuid = "";
    foreach (byte b in byteGuid)
    {
        queryGuid += @"\" + b.ToString("x2");
    }
    return queryGuid;
}

This supposedly converts the guid string into something usable by Active Directory. When I run my manager's NativeGuid through this, I get a result. But then in the next step of the application, I run one of the directReports' Guids through in the same way but get no results. The user DOES exist and I can get the entry if i pull the DirectoryEntry, but I don't want the full entry as it is too slow to process. I need to be able to narrow the fields using the DirectorySearcher to speed this thing up. Any ideas why I'm getting goose egg on the directory search on some users but not others?

Upvotes: 1

Views: 2319

Answers (1)

marc_s
marc_s

Reputation: 754568

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Basically, you can define a domain context and easily find users and/or groups in AD:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.Guid, YourGuid.ToString());

if(user != null)
{
   // do something here....     
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!

Upvotes: 1

Related Questions