係 Domain Controller 上以 DisplayName 獲得 User ID (SAMAccountName) 方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.DirectoryServices; namespace ClassLibrary1 { public class aduser { public String getUserID(String FullName) { string LDAPstring = "LDAP://vmser001:389/OU=Workstations, DC=deisler, DC=com"; string domainusername = @"deisler\administrator"; string domainpassword = "Passwd"; string lbl = ""; if (FullName.IndexOf('\\') > 0) return FullName.Split('\\')[1]; DirectoryEntry entry = new DirectoryEntry(LDAPstring, domainusername, domainpassword, AuthenticationTypes.None); try { DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(DisplayName=" + FullName + ")"; search.PropertiesToLoad.Add("DisplayName"); search.PropertiesToLoad.Add("SAMAccountName"); SearchResultCollection result = search.FindAll(); foreach (SearchResult item in result) { foreach (string PropertyName in item.Properties.PropertyNames) { foreach (object key in item.GetDirectoryEntry().Properties[PropertyName]) { if (PropertyName == "samaccountname") { lbl = key.ToString(); } } } } } catch (Exception ex) { return "Error : " + ex.Message; } return lbl; } } } |