DCはあなたのドメインです。DCよりもドメインexample.comに接続する場合は、DC = example、DC=comです。
実際には、ドメインコントローラーのホスト名やIPアドレスは必要ありません(それらはたくさんある可能性があります)。
ドメイン自体に接続していると想像してみてください。したがって、ドメインexample.comに接続するには、次のように記述します。
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
これで完了です。
接続に使用するユーザーとパスワードを指定することもできます。
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");
また、LDAPは必ず大文字で記述してください。どこかで大文字で書こうとすると問題が解決するまで、いくつかの問題と奇妙な例外がありました。
プロパティを使用すると、directoryEntry.Path
ドメインをさらに深く掘り下げることができます。したがって、特定のOU(組織単位)内のユーザーを検索する場合は、そこに設定できます。
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";
これは、次のAD階層と一致します。
階層を最も深いものから最も高いものへと単純に記述します。
今、あなたはたくさんのことをすることができます
たとえば、アカウント名でユーザーを検索し、ユーザーの名前を取得します。
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
PageSize = int.MaxValue,
Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};
searcher.PropertiesToLoad.Add("sn");
var result = searcher.FindOne();
if (result == null) {
return; // Or whatever you need to do in this case
}
string surname;
if (result.Properties.Contains("sn")) {
surname = result.Properties["sn"][0].ToString();
}