c#访问LDAP方法(未调试, 不知是否可用)
来源:互联网 发布:new3dsll怎么关掉网络 编辑:程序博客网 时间:2024/06/07 02:01
using System;using System.Text;using System.Net;using System.Security.Permissions;using System.DirectoryServices;using System.DirectoryServices.Protocols;using SDS = System.DirectoryServices;namespace Microsoft.Samples.DirectoryServices{ class A { static LdapConnection ldapConnection; static string ldapServer; static NetworkCredential credential; static string targetOU; // dn of an OU. eg: "OU=sample,DC=fabrikam,DC=com" // object DNs that are created in the sample static string ou1, ou2, ou3; public static void Main(string[] args) { try { if (!GetParameters(args)) { return; } EnumerateOU(); Console.WriteLine("\r\nApplication Finished Successfully!!!"); } catch (System.Exception ex) { } } public static bool GetParameters(string[] args) { if (args.Length != 5) { //("LDAP://127.0.01/ou=user,dc=companyname,dc=com", "cn=sysuser,ou=systemaccounts,dc=companyname,dc=com", "sysuser", AuthenticationTypes.None); Console.WriteLine("Usage: App.exe <ldapServer> <user> <pwd> <targetOU>"); // return error return false; } // initialize variables ldapServer = args[0]; credential = new NetworkCredential(args[1], args[2], args[3]); targetOU = args[4]; // return success return true; } public static void EnumerateOU() { DirectoryEntry entry = new DirectoryEntry("LDAP://127.0.01/ou=user,dc=companyname,dc=com", "cn=sysuser,ou=systemaccounts,dc=companyname,dc=com", "sysuser", AuthenticationTypes.None); try { object native = entry.NativeObject; DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = "(objectClass=account)"; searcher.PropertiesToLoad.Add("cn"); SearchResultCollection ret = searcher.FindAll(); foreach (SearchResult sr in ret) { foreach (string key in sr.Properties.PropertyNames) { foreach (object val in sr.Properties[key]) { string strTmp = key + " = " + val; Console.WriteLine(strTmp); } } } } catch (System.Exception ex) { } return; } }}