Reputation: 1621
I've been searching through the internet to learn how to interact with Active Directory. I find the following piece of code but I want to know what ActiveDirectoryPath
must be ?
Any brief description of the code is welcome
DirectoryEntry entry = new DirectoryEntry(ActiveDirectoryPath);
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = String.Format("(&(objectCategory=group)(cn={0}))", activeDirectoryGroup);
search.PropertiesToLoad.Add("distinguishedName");
SearchResult searchResult = search.FindOne();
if (searchResult == null)
return new HashSet<User>();
DirectoryEntry group = searchResult.GetDirectoryEntry();
Hashtable searchedGroups = new Hashtable();
return GetUsersInGroup(group.Properties["distinguishedName"].Value.ToString(), searchedGroups, path);
Upvotes: 2
Views: 4906
Reputation: 754220
Not entirely clear what you mean by detect Active Directory path - there's really no "current" AD path or anything; there's no "current directory" like in your file system.
You can determine the system default path by inspecting the LDAP://RootDSE
entry and looking for the defaultNamingContext
there:
using (DirectoryEntry deRoot = new DirectoryEntry("LDAP://RootDSE"))
{
if (deRoot.Properties["defaultNamingContext"] != null)
{
string defaultNamingContext =
deRoot.Properties["defaultNamingContext"].Value.ToString();
}
}
Or you can just retrieve the currently logged in user from Active Directory, and inspect it's LDAP path (this code works on .NET 3.5 and newer with the new System.DirectoryServices.AccountManagement
namespace):
using System.DirectoryServices.AccountManagement;
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
UserPrincipal currentUser = UserPrincipal.Current;
string userLdapPath = currentUser.DistinguishedName;
}
This will return the full LDAP path for the user, which contains the "container" that user is created in - something like:
LDAP://CN=User Name,OU=SomeOU,DC=YourCompany,DC=Com
and here the OU=SomeOU,DC=YourCompany,DC=Com
part is the "path" in the Active Directory where this user exists inside of.
Upvotes: 2