// Wird aufgerufen, sobald nach einem Benutzer gesucht werden soll private void btnSearch_Click(object sender, EventArgs e) { if (tbADPassword.Text.Length == 0 || tbAdUsername.Text.Length == 0 || tbServer.Text.Length == 0) { MessageBox.Show("You have to enter username, password and server for Active Directory"); return; } if (tbSearchFor.Text.Length == 0) { MessageBox.Show("Enter at least one character for object searching"); return; } try { DirectoryEntry de = new DirectoryEntry(tbServer.Text, tbAdUsername.Text, tbADPassword.Text); de.AuthenticationType = AuthenticationTypes.Secure; DirectorySearcher ds = new DirectorySearcher(); ds.SearchRoot = de; // ANR power! ds.Filter = "(anr=" + tbSearchFor.Text + ")"; SearchResultCollection results = ds.FindAll(); lbResults.DataSource = null; lblTotalResults.Text = results.Count.ToString(); List<ActiveDirectoryUser> list = ActiveDirectoryUser.toList(results); ActiveDirectoryUser dummyUser = new ActiveDirectoryUser(SELECT_DUMMY, "", "", ""); list.Add(dummyUser); lbResults.DataSource = list; lbResults.SelectedItem = dummyUser; } catch (Exception ex) { MessageBox.Show("Active Directory query failed: " + ex.Message); } }
public static List<ActiveDirectoryUser> toList(SearchResultCollection _src) { List<ActiveDirectoryUser> r = new List<ActiveDirectoryUser>(); foreach (SearchResult sr in _src) { ResultPropertyValueCollection rpcObjectSid = sr.Properties["objectSid"]; ResultPropertyValueCollection rpcDisplayName = sr.Properties["displayName"]; ResultPropertyValueCollection rpcObjectGuid = sr.Properties["objectGUID"]; String sid = "<unknown>"; String displayName = "<unknown>"; String guid = "<unknown>"; if (rpcObjectSid.Count > 0) { byte[] val = (byte[])rpcObjectSid[0]; sid = new SecurityIdentifier(val, 0).Value; } if (rpcDisplayName.Count > 0) { displayName = rpcDisplayName[0].ToString(); } if (rpcObjectGuid.Count > 0) { byte[] val = (byte[])rpcObjectGuid[0]; guid = new Guid(val).ToString(); } ActiveDirectoryUser adu = new ActiveDirectoryUser(displayName, guid, sid, sr.Path); r.Add(adu); } return r; }