本文整理汇总了C#中System.DirectoryServices.DirectoryEntry.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# DirectoryEntry.Dispose方法的具体用法?C# DirectoryEntry.Dispose怎么用?C# DirectoryEntry.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.DirectoryEntry
的用法示例。
在下文中一共展示了DirectoryEntry.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
示例2: IsAuthenticated
//Check user login with AD
public bool IsAuthenticated(string LoginId, string Password)
{
Boolean status = false;
string Domain = "ARVATO";
string path = "";
DirectoryEntry entry = new DirectoryEntry(path, Domain + @"\" + LoginId, Password);
try
{
Object obj = entry.NativeObject;
status = true;
}
catch (Exception)
{
status = false;
}
finally
{
entry.Dispose();
}
return status;
}
示例3: EnumerateOU
public ArrayList EnumerateOU(string OuDn)
{
ArrayList alObjects = new ArrayList();
try
{
DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + OuDn);
foreach (DirectoryEntry child in directoryObject.Children)
{
string childPath = child.Path.ToString();
childPath = childPath.Remove(0, 7);
if ("OU=" == childPath.Substring(0, 3))
{
alObjects.AddRange(EnumerateOU(childPath));
}
else
{
alObjects.Add(childPath);//remove ldap prefix
}
child.Close();
child.Dispose();
}
directoryObject.Close();
directoryObject.Dispose();
}
catch (DirectoryServicesCOMException e)
{
throw new DirectoryServicesCOMException("An error occured. " + e.Message);
}
return alObjects;
}
示例4: EnumerateGroups
/// <summary>
/// Enumerates the groups.
/// </summary>
/// <param name="domain">The domain.</param>
/// <returns></returns>
public static List<Group> EnumerateGroups(string domain)
{
List<Group> groups = new List<Group>();
try
{
DirectoryEntry directoryObject = new DirectoryEntry("LDAP://" + domain);
DirectorySearcher searcher = new DirectorySearcher(directoryObject);
searcher.Filter = "(ObjectCategory=group)";
foreach (SearchResult result in searcher.FindAll())
{
groups.Add(new Group(result.GetDirectoryEntry().Name.Replace("CN=", string.Empty), result.GetDirectoryEntry().Path));
}
directoryObject.Close();
directoryObject.Dispose();
}
catch (DirectoryServicesCOMException e)
{
Console.WriteLine("An Error Occurred: " + e.Message.ToString());
}
groups.Sort();
return groups;
}
示例5: change
public bool change(string username,string newpassword)
{
//Method to change the password of the remote machine
DirectoryEntry dirEntry = null;
string computerName = @"WinNT://" + this.target + "/" + username + ",user";
try
{
dirEntry = new DirectoryEntry(computerName, this.adUser, this.adPassword);
dirEntry.Invoke("SetPassword", new Object[] { newpassword});
dirEntry.CommitChanges();
try
{
this.displayPopupInRemote();
}
catch (Exception e)
{
this.setError("Unable to Display Message in Remote Machine - " +e.Message);
}
return true;
}
catch (Exception Ex)
{
this.setError(Ex.Message);
}
finally
{
if (dirEntry != null)
dirEntry.Dispose();
}
return false;
}
示例6: 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;
}
示例7: GetNetworkDirectoryServices
private static ArrayList GetNetworkDirectoryServices()
{
DirectoryEntry de = new DirectoryEntry("WinNT:");
ArrayList ar = new ArrayList();
foreach (DirectoryEntry nDom in de.Children)
{
foreach (DirectoryEntry nPc in nDom.Children)
{
if (nPc.Name != "Schema")
ar.Add(nPc.Name);
}
}
de.Dispose();
return ar;
}
示例8: 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;
}
示例9: FindMatchingComputers
public List<string> FindMatchingComputers(string sFilterString)
{
if (!sFilterString.EndsWith("*") && !sFilterString.EndsWith("$") && !sFilterString.EndsWith("%"))
{
sFilterString = sFilterString += "$";
}
if (sFilterString.EndsWith("%"))
{
sFilterString = sFilterString.Replace('%', '*');
}
string filter = string.Format("(&(objectCategory=Computer)(sAMAccountName={0}))", sFilterString);
List<string> Matches = new List<string>();
DirectoryEntry de = new DirectoryEntry(string.Format("LDAP://{0}", this.GetClosestGC()));
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)
{
Matches.Add(sr.Properties["sAMAccountName"][0].ToString().Replace("$", ""));
}
}
results.Dispose();
}
catch
{
//ERROR....
}
finally
{
de.Dispose();
ds.Dispose();
}
return Matches;
}
示例10: DoesVirtualDirectoryExist
protected bool DoesVirtualDirectoryExist()
{
int siteNumber = ConvertSiteNameToSiteNumber(WebsiteName);
string path = BuildIisPath(siteNumber, VdirPath);
var entry = new DirectoryEntry(path);
try
{
//trigger the *private* entry.Bind() method
object adsobject = entry.NativeObject;
return true;
}
catch
{
return false;
}
finally
{
entry.Dispose();
}
}
示例11: AuthenticateUser
public string AuthenticateUser(string strUID)
{
string strID = string.Empty;
string strEmail = string.Empty;
string studentID = string.Empty;
DirectoryEntry entry = new DirectoryEntry();
try
{
// call getDNFRromLDAP method to anonymously (port 389)
// search against ldap for the correct DN
string strDN = getDNFromLDAP(strUID);
//now use the found DN for the secure bind (port 636)
entry.Path = "LDAP://rock.temple.edu/" + strDN;
entry.Username = strDN;
entry.Password = PasswordTextBox.Text;
entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;
//try to fetch a property..if no errors raised then it works
strID = entry.Properties["sAMAccountName"][0].ToString();
strEmail = entry.Properties["mail"][0].ToString();
studentID = entry.Properties["employeeID"][0].ToString();
Session["AuthorizedUserTUID"] = studentID;
ViewState["TUID"] = studentID;
}
catch
{
}
finally
{
entry.Close();
entry.Dispose();
}
return strID;
}
示例12: retrieve
public void retrieve()
{
//Retrieve computers from the AD server and store in the application database
DirectoryEntry dirEntry = null;
try
{
dirEntry = new DirectoryEntry("LDAP://" + AppSession.ServerIP, AppSession.UserName, AppSession.Password);
DirectorySearcher finder = new DirectorySearcher(dirEntry);
finder.Filter = "(objectClass=computer)";
SearchResultCollection results = finder.FindAll();
RemoteSystemTableHandler rSystemHandler = new RemoteSystemTableHandler();
foreach (SearchResult sr in results)
{
DirectoryEntry computerEntry = sr.GetDirectoryEntry();
String computerName = computerEntry.Name.Replace("CN=", "");
if (computerName != "")
{
RemoteSystem rSystem = new RemoteSystem();
rSystem.setSystemName(computerName);
if (!rSystemHandler.exists(rSystem))
{
rSystemHandler.addSystem(rSystem);
}
}
}
}
catch (Exception e)
{
this.setError("Unable to Retrieve ComputerList " + e.Message);
}
finally
{
if (dirEntry != null)
{
dirEntry.Dispose();
}
}
}
示例13: Authenticate
/// <summary>
/// Active Directory 서버에서 사용자 인증을 수행한다.
/// </summary>
/// <param name="adPath">AD 서버 경로 (ex: LDAP://ServerName )</param>
/// <param name="username">사용자 Id</param>
/// <param name="password">사용자 비밀번호</param>
/// <param name="authType">인증 형식</param>
/// <returns>인증 성공 여부</returns>
public static bool Authenticate(string adPath, string username, string password, AuthenticationTypes authType) {
adPath.ShouldNotBeWhiteSpace("adPath");
username.ShouldNotBeWhiteSpace("username");
if(IsDebugEnabled)
log.Debug("Authenticate with adPath=[{0}], username=[{1}], password=[{2}], authType=[{3}]",
adPath, username, password, authType);
bool result = false;
DirectoryEntry entry = null;
try {
entry = new DirectoryEntry(adPath, username, password, authType);
var nativeObject = entry.NativeObject;
result = (nativeObject != null);
}
catch(Exception ex) {
if(log.IsWarnEnabled) {
log.Warn("AD DirectoryEntry 조회에 실패했습니다. adPath=[{0}]", adPath);
log.Warn(ex);
}
result = false;
}
finally {
if(entry != null)
entry.Dispose();
}
if(IsDebugEnabled)
log.Debug("Authenticate with adPath=[{0}], username=[{1}], password=[{2}], authType=[{3}], result=[{4}]",
adPath, username, password, authType, result);
return result;
}
示例14: DoMachineInit
private void DoMachineInit()
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "Entering DoMachineInit");
Debug.Assert(_contextType == ContextType.Machine);
Debug.Assert(_container == null);
DirectoryEntry de = null;
try
{
string hostname = _name;
if (hostname == null)
hostname = Utils.GetComputerFlatName();
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoMachineInit: hostname is " + hostname);
// use the options they specified
AuthenticationTypes authTypes = SDSUtils.MapOptionsToAuthTypes(_options);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "PrincipalContext", "DoMachineInit: authTypes is " + authTypes.ToString());
de = new DirectoryEntry("WinNT://" + hostname + ",computer", _username, _password, authTypes);
// Force ADSI to connect so we detect if the server is down or if the servername is invalid
de.RefreshCache();
StoreCtx storeCtx = CreateContextFromDirectoryEntry(de);
_queryCtx = storeCtx;
_userCtx = storeCtx;
_groupCtx = storeCtx;
_computerCtx = storeCtx;
_connectedServer = hostname;
de = null;
}
catch (Exception e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error,
"PrincipalContext",
"DoMachineInit: caught exception of type "
+ e.GetType().ToString() +
" and message " + e.Message);
// Cleanup the DE on failure
if (de != null)
de.Dispose();
throw;
}
}
示例15: LogIn
public ActionResult LogIn(LogInModel model, string returnUrl)
{
if (! ModelState.IsValid) {
ViewBag.u_error = model.username == null ? "has-error" : "";
ViewBag.p_error = model.password == null ? "has-error" : "";
return View(model);
}
DirectoryEntry adsEntry = new DirectoryEntry(LDAP_Add, model.username, model.password);
DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry);
adsSearcher.Filter = "(sAMAccountName=" + model.username + ")";
try
{
SearchResult adsSearchResult = adsSearcher.FindOne();
FormsAuthentication.SetAuthCookie(model.username, true);
USER findUsr;
findUsr = ctx.USER.SingleOrDefault( u => u.USERNAME == model.username);
if (findUsr == null)
{
USER u = new USER();
u.APELLIDO = (string)adsSearchResult.Properties["sn"][0];
u.NOMBRE = (string)adsSearchResult.Properties["givenName"][0];
try
{
u.LEGAJO = int.Parse((string)adsSearchResult.Properties["ipPhone"][0]);
}
catch
{
u.LEGAJO = int.Parse((string)adsSearchResult.Properties["homePhone"][0]);
}
try
{
u.EDAD = DateHelper.GetAgeFromLDAP((string)adsSearchResult.Properties["info"][0]);
}
catch
{
u.EDAD = 50;
}
u.EMAIL = (string)adsSearchResult.Properties["mail"][0];
u.USERNAME = model.username;
u.HEROE = "N";
u.VOTO = "N";
ctx.USER.Add(u);
ctx.SaveChanges();
findUsr = u;
}
ContextHelper.LoggedUser = findUsr;
return RedirectToAction("Index", "Home");
}
catch (Exception ex)
{
// Failed to authenticate. Most likely it is caused by unknown user
// id or bad strPassword.
@ViewData["Error"] = ex.Message;
}
finally
{
adsEntry.Close();
adsEntry.Dispose();
}
// If we got this far, something failed, redisplay form
return View(model);
}