本文整理汇总了C#中System.DirectoryServices.DirectorySearcher.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# DirectorySearcher.Dispose方法的具体用法?C# DirectorySearcher.Dispose怎么用?C# DirectorySearcher.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.DirectorySearcher
的用法示例。
在下文中一共展示了DirectorySearcher.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: getNextUID
public Int32 getNextUID()
{
checkConnection();
Int32 id = 0;
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(|(objectClass=user))";
SearchResultCollection resultSet = mySearcher.FindAll();
foreach (SearchResult result in resultSet)
{
DirectoryEntry user = result.GetDirectoryEntry();
if (user.Properties["uidnumber"].Value != null)
{
String foo = user.Properties["uidnumber"].Value.ToString();
String username = user.Properties["uid"].Value.ToString();
int thisID;
Int32.TryParse(foo, out thisID);
if (thisID > id){
id = thisID;
}
}
}
mySearcher.Dispose();
return (id != 0) ? (id + 1) : 0;
}
示例2: GetComputers
public static List<string> GetComputers()
{
List<string> ComputerNames = new List<string>();
DirectoryEntry entry = new DirectoryEntry("LDAP://transnetwork.local/OU=Phoenix-DC,DC=transnetwork,DC=local");
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)"); //se buscan solamente objetos de ltipo computadora / server
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PageSize = int.MaxValue;
foreach (SearchResult resEnt in mySearcher.FindAll())
{
//"CN=SGSVG007DC"
string ComputerName = resEnt.GetDirectoryEntry().Name;
if (ComputerName.StartsWith("CN="))
ComputerName = ComputerName.Remove(0, "CN=".Length);
ComputerNames.Add(ComputerName);
}
mySearcher.Dispose();
entry.Dispose();
// Console.ReadLine();
return ComputerNames;
}
示例3: Test
public static Task Test()
{
return Task.Run(() => {
string strServerDNS = "ldap.hp.com:389";
string strSearchBaseDN = "ou=Email,ou=Services,o=hp.com";
string strLDAPPath;
strLDAPPath = "LDAP://" + strServerDNS + "/" + strSearchBaseDN;
DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, null, null, AuthenticationTypes.Anonymous);
DirectorySearcher searcher = new DirectorySearcher(objDirEntry);
SearchResult result = null;
searcher.Filter = "[email protected]";
searcher.PropertiesToLoad.Add("ntUserDomainId");
searcher.ClientTimeout = TimeSpan.FromSeconds(20);
try
{
result = searcher.FindOne();
}
catch (Exception ex)
{
}
finally
{
searcher.Dispose();
}
});
}
示例4: getDNFromLDAP
public static string getDNFromLDAP(string strUID)
{
DirectoryEntry entry = new DirectoryEntry("LDAP://rock.temple.edu/ou=temple,dc=tu,dc=temple,dc=edu");
entry.AuthenticationType = AuthenticationTypes.None;
DirectorySearcher mySearcher = new DirectorySearcher(entry);
entry.Close();
entry.Dispose();
mySearcher.Filter = "(sAMAccountName=" + strUID + ")";
SearchResult result = mySearcher.FindOne();
mySearcher.Dispose();
int nIndex = result.Path.LastIndexOf("/");
string strDN = result.Path.Substring((nIndex + 1)).ToString().TrimEnd();
return strDN;
}
示例5: GetFullName
public static string GetFullName( string strUserId )
{
if( ServerList.Count == 0 )
LoadServerList();
string sLDAPPath = string.Format( "LDAP://{0}/DC=XXXX,DC=root01,DC=org", ServerList["XXXX"] );
string strFullName = "";
DirectoryEntry objDE = null;
try
{
objDE = new DirectoryEntry(sLDAPPath);
DirectorySearcher objDS = new DirectorySearcher( objDE );
// get the LDAP filter string based on selections
string strFilter = string.Format("(|(&(objectClass=User)(sAMAccountName={0})))", strUserId);
objDS.Filter = strFilter;
objDS.ReferralChasing = ReferralChasingOption.None;
//start searching
SearchResultCollection objSRC = objDS.FindAll();
try
{
if (objSRC.Count != 0)
{
// grab the first search result
SearchResult objSR = objSRC[0];
string strFirstName = objSR.Properties[ "givenName" ][ 0 ].ToString();
string strLastName = objSR.Properties[ "sn" ][ 0 ].ToString();
strFullName = string.Concat( strLastName, ", ", strFirstName );
}
}
catch (Exception e)
{
// ignore errors
}
objSRC.Dispose();
objDS.Dispose();
}
catch (Exception e)
{
// ignore errors
}
return strFullName;
}
示例6: FindMatchingComputers
public BindableCollection<IComputer> FindMatchingComputers(string filterName)
{
if (!filterName.EndsWith("*") && !filterName.EndsWith("$") && !filterName.EndsWith("%"))
{
filterName = filterName += "$";
}
if (filterName.EndsWith("%"))
{
filterName = filterName.Replace('%', '*');
}
string filter = string.Format("(&(objectCategory=Computer)(sAMAccountName={0}))", filterName);
BindableCollection<IComputer> Matches = new BindableCollection<IComputer>();
DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}",GetClosestDC()));
DirectorySearcher ds = new DirectorySearcher(de);
SearchResultCollection results;
try
{
ds.ReferralChasing = ReferralChasingOption.All;
ds.SearchScope = SearchScope.Subtree;
ds.PropertiesToLoad.Add("sAMAccountName");
ds.Filter = filter;
results = ds.FindAll();
if (results.Count > 0)
{
foreach (SearchResult sr in results)
{
Computer c = new Computer() { Name = sr.Properties["sAMAccountName"][0].ToString().Replace("$", "") };
Matches.Add(c);
}
}
results.Dispose();
}
catch
{
//ERROR....
}
finally
{
de.Dispose();
ds.Dispose();
}
return Matches;
}
示例7: SearchLdapContext
/// <summary>
/// Search the LDAP store for the entries required using the context specified
/// </summary>
/// <param name="adsPath">The adspath that the server will use</param>
/// <param name="objectClass">The object class to search for</param>
/// <param name="attrib">The attribute to search on</param>
/// <param name="attribValue">The value to search for</param>
/// <returns>The collection of results found.</returns>
protected SearchResultCollection SearchLdapContext(string adsPath, string objectClass, string attrib, string attribValue)
{
DirectoryEntry root = GetServerContext(adsPath);
StringBuilder sb = new StringBuilder();
sb.AppendFormat(m_defaultSearch, objectClass, attrib, attribValue);
DirectorySearcher ds = new DirectorySearcher(root, sb.ToString());
if ( m_pageSize > 0 )
ds.PageSize = m_pageSize;
ds.SearchScope = SearchScope.Subtree;
foreach(string prop in m_properties )
ds.PropertiesToLoad.Add(prop);
SearchResultCollection src = ds.FindAll();
ds.Dispose();
root.Dispose();
return src;
}
示例8: GetUserInfo
public static Task GetUserInfo(Dictionary<string,string> Filter,Dictionary<string, ResultPropertyValueCollection> ResultFormat)
{
return Task.Run(() => {
string strServerDNS = "ldap.hp.com:389";
string strSearchBaseDN = "ou=People,o=hp.com";
string strLDAPPath;
strLDAPPath = "LDAP://" + strServerDNS + "/" + strSearchBaseDN;
DirectoryEntry objDirEntry = new DirectoryEntry(strLDAPPath, null, null, AuthenticationTypes.Anonymous);
DirectorySearcher searcher = new DirectorySearcher(objDirEntry);
SearchResult result = null;
searcher.Filter = "[email protected]";
foreach(var returnVal in ResultFormat)
{
searcher.PropertiesToLoad.Add(returnVal.Key);
}
searcher.ClientTimeout = TimeSpan.FromSeconds(20);
try
{
result = searcher.FindOne();
for(int i = 0;i<ResultFormat.Count;i++)
{
string key = ResultFormat.ElementAt(i).Key;
ResultFormat[key] = result.Properties[key];
}
}
catch(Exception ex)
{
}
finally
{
searcher.Dispose();
}
});
}
示例9: AddUserToGroup
public static void AddUserToGroup(string UserName, string GroupName)
{
DirectoryEntry rootEntry = GetDirectoryObject("/" + GetLDAPDomain());
DirectorySearcher Mysearcher = new DirectorySearcher(rootEntry);
Mysearcher.SearchRoot = rootEntry;
Mysearcher.Filter = "(&(objectCategory=group)(CN=" + GroupName + "))";
SearchResult result = Mysearcher.FindOne();
DirectoryEntry g = result.GetDirectoryEntry();
Mysearcher.Filter = "(&(objectCategory=user)(SAMAccountName=" + UserName + "))";
result = Mysearcher.FindOne();
DirectoryEntry user = result.GetDirectoryEntry();
g.Invoke("Add", new Object[] { user.Path });
g.CommitChanges();
g.Close();
g.Dispose();
user.Close();
user.Dispose();
Mysearcher.Dispose();
rootEntry.Close();
rootEntry.Dispose();
}
示例10: GetAvailableSamAccountName
/// <summary>
/// Find an availble sAMAccountName
/// It loops and appends a number to the end of a sAMAccountNAme if the original doesn't exist
/// </summary>
/// <param name="userPrincipalName"></param>
/// <returns></returns>
private string GetAvailableSamAccountName(string userPrincipalName)
{
DirectoryEntry de = null;
DirectorySearcher ds = null;
try
{
logger.Debug("Attempting to find an available sAMAccountName for " + userPrincipalName);
// Get the first part of the user principal name
string upnFirstPart = userPrincipalName.Split('@')[0];
string sAMAccountName = upnFirstPart;
de = new DirectoryEntry("LDAP://" + this.domainController, this.username, this.password);
ds = new DirectorySearcher(de);
ds.SearchScope = SearchScope.Subtree;
ds.Filter = string.Format("(&(objectClass=User)(sAMAccountName={0}))", upnFirstPart);
int count = 0;
while (ds.FindOne() != null)
{
count++;
sAMAccountName = string.Format("{0}{1}", upnFirstPart, count.ToString());
ds.Filter = string.Format("(&(objectClass=User)(sAMAccountName={0}))", sAMAccountName);
}
// We found our available sAMAccountName
return sAMAccountName;
}
catch (Exception ex)
{
this.logger.Error("Error retrieving user information " + userPrincipalName, ex);
throw;
}
finally
{
if (ds != null)
ds.Dispose();
if (de != null)
de.Dispose();
}
}
示例11: DoesUserPrincipalNameExist
/// <summary>
/// Checks if a userprincipalname exists
/// </summary>
/// <param name="userPrincipalName"></param>
/// <returns></returns>
private bool DoesUserPrincipalNameExist(string userPrincipalName)
{
DirectoryEntry de = null;
DirectorySearcher ds = null;
try
{
logger.Debug("Attempting to find out if userprincipalname exists " + userPrincipalName);
de = new DirectoryEntry("LDAP://" + this.domainController, this.username, this.password);
ds = new DirectorySearcher(de);
ds.SearchScope = SearchScope.Subtree;
ds.Filter = string.Format("(userPrincipalName={0})", userPrincipalName);
if (ds.FindOne() != null)
return true;
else
return false;
}
catch (Exception ex)
{
this.logger.Error("Error checking if user exists " + userPrincipalName, ex);
throw;
}
finally
{
if (ds != null)
ds.Dispose();
if (de != null)
de.Dispose();
}
}
示例12: GetPhoto
/// <summary>
/// Gets the photo for the user from the thumbnailPhoto attribute in Active Directory
/// </summary>
/// <param name="userPrincipalName"></param>
/// <returns></returns>
public byte[] GetPhoto(string userPrincipalName)
{
DirectoryEntry de = null;
DirectorySearcher ds = null;
try
{
logger.Debug("Attempting to find photo for " + userPrincipalName);
de = new DirectoryEntry("LDAP://" + this.domainController, this.username, this.password);
ds = new DirectorySearcher(de);
ds.SearchScope = SearchScope.Subtree;
ds.Filter = string.Format("(&(objectClass=User)(userPrincipalName={0}))", userPrincipalName);
SearchResult found = ds.FindOne();
byte[] data = null;
if (found != null)
{
using (DirectoryEntry u = new DirectoryEntry(found.Path))
{
if (u.Properties["thumbnailPhoto"].Value != null)
data = u.Properties["thumbnailPhoto"].Value as byte[];
}
}
return data;
}
catch (Exception ex)
{
this.logger.Error("Error getting photto for " + userPrincipalName, ex);
throw;
}
finally
{
if (ds != null)
ds.Dispose();
if (de != null)
de.Dispose();
}
}
示例13: GetGroup
/// <summary>
/// 根据组名返回用户组
/// </summary>
/// <param name="entry"></param>
/// <param name="groupname"></param>
/// <returns></returns>
public static DirectoryEntry GetGroup(DirectoryEntry entry, string groupname)
{
if (string.IsNullOrEmpty(groupname))
{
return null;
}
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.Filter = "(&(objectClass=group)(name=" + groupname + "))";
searcher.CacheResults = false;
searcher.PropertyNamesOnly = true;
searcher.PropertiesToLoad.Add("cn");
searcher.PropertiesToLoad.Add("distinguishedName");
searcher.PropertiesToLoad.Add("Description");
searcher.PropertiesToLoad.Add("memberOf");
SearchResult result = searcher.FindOne();
DirectoryEntry group = null;
if (result != null)
{
group = result.GetDirectoryEntry();
}
entry.Dispose();
searcher.Dispose();
return group;
}
示例14: User_Get
/// <summary>
/// Obtiene un usuario por nombre sin tener en cuenta las credenciales del usuario
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
DirectoryEntry User_Get(string userName)
{
DirectoryEntry userDirectoryEntry = null;
DirectorySearcher deSearch = new DirectorySearcher(_directoryEntrySearchRoot);
deSearch.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))",FilterOutDomain(userName));
//deSearch.Filter = "(&(objectClass=user)(cn=" + FilterOutDomain(userName) + "))";
deSearch.CacheResults = false;
deSearch.SearchScope = System.DirectoryServices.SearchScope.Subtree;
SearchResult results = deSearch.FindOne();
//si result no es nulo se puede crear una DirectoryEntry
if (results != null)
userDirectoryEntry = new DirectoryEntry(results.Path);
deSearch.Dispose();
return userDirectoryEntry;
}
示例15: LDB_Query
void LDB_Query(object sender, RoutedEventArgs e)
{
lbQBUsers.Items.Clear();
DirectorySearcher ds = new DirectorySearcher();
ds.SearchRoot = new DirectoryEntry(selectedPath); // start searching from whatever was selectted
ds.Filter = (tbFilter.Text.Length > 0) ? String.Format(
"(|(&(objectCategory=user)(name={0})))", tbFilter.Text) :
"(|(&(objectCategory=user)(name=*)))";
ds.PropertiesToLoad.Add("sAMAccountName");
if (cbEntireSubt.IsChecked == false)
ds.SearchScope = SearchScope.OneLevel;
SearchResultCollection src = ds.FindAll();
try
{
int arraySiz = (src.Count) * 2;
accts = new string[arraySiz];
int k = 0;
foreach (SearchResult sr in src)
{
DirectoryEntry de = sr.GetDirectoryEntry();
lbQBUsers.Items.Add(de.Name.Substring(3));
foreach (String property in ds.PropertiesToLoad)
{
foreach (Object myCollection in sr.Properties[property])
{
if (property == "sAMAccountName")
{
accts[k++] = de.Name.Substring(3);
accts[k++] = myCollection.ToString();
break;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
src.Dispose();
ds.Dispose();
}