I have a multi-domain active directory environment and need to find a user based on DOMAIN\username.

The following code works great for finding a user by SID.

DirectorySearcher directorySearcher = new DirectorySearcher(new DirectoryEntry(
    "GC://" + Forest.GetCurrentForest().Name));

directorySearcher.Filter =
    "(&" +
        (&(objectCategory=person)(objectClass=user)) +
        "(objectSid=" + this.SID + "))";
var result = directorySearcher.FindOne();

But now I'm in a situation where all I have is DOMAIN\username.

What goes in the filter for this?

One approach I considered is connecting to the specific domain rather than the global catalog and searching by the unqualified SAMAccountName. But my problem there is I don't know how to get from DOMAIN to DC=Domain,DC=Org or domain.org.

When I'm in Active Directory Users and Computers, there seems to be no problem searching the entire directory by DOMAIN\username. What is happening there behind the scenes?

有帮助吗?

解决方案

This was the missing piece.

using System.Security.Principal;

var sid = (SecurityIdentifier)new NTAccount(userName).Translate(
    typeof(SecurityIdentifier));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top