简体   繁体   中英

Active Directory Access

I need to access information from active directory. I am using code

DirectoryEntry entry = new DirectoryEntry("LDAP://domain", "AD_id", "password");

DirectorySearcher search = new DirectorySearcher(entry);
try
{
   search.Filter = "(SAMAccountName=AD_id)";
   search.PropertiesToLoad.Add("cn");
   search.PropertiesToLoad.Add("sn");
   search.PropertiesToLoad.Add("givenName");
   search.PropertiesToLoad.Add("email");

   SearchResult result = search.FindOne();

   if (result != null)
       lbl_result.Text = result.Path.ToString();
   else
       lbl_result.Text = "failier";
}
catch (Exception ex)
{
   lbl_result.Text = ex.Message;
}

I successfully get a few information about the user in the given format

LDAP://domain/CN=username,OU=aaa,OU=bbb,OU=ccc,DC=domain,DC=com

But this is not complete information that I need, for example email address is not in the above string.(aaa, bbb and ccc are some other information) Please help me if I am doing some thing wrong. I am new to this kind of programming. I will be thankful.

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, "SomeUserName");

if(user != null)
{
   // do something here....     
   string emailAddress = user.EmailAddress;
}

The UserPrincipal class contains a great many properties which you can read out (and set new values for, too).

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

And of course - you can also search for users!

You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the SAMAccountName of "ad_id"
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.SamAccountName = "ad_id";

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
    UserPrincipal foundUser = found as UserPrincipal;

    if(foundUser != null)
    {
       // do something here....     
       string emailAddress = foundUser.EmailAddress;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM