当前位置: 首页>>代码示例>>C#>>正文


C# DirectoryEntry.Dispose方法代码示例

本文整理汇总了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;
        }
开发者ID:asa181192,项目名称:Servicios,代码行数:25,代码来源:ServersDev.cs

示例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;
        }
开发者ID:BrettLeeARV,项目名称:Arvato.TestProject.UserManagement,代码行数:27,代码来源:LDAPComponent.cs

示例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;
        }
开发者ID:slogsdon,项目名称:ThumbsUp,代码行数:32,代码来源:LdapAuthentication.cs

示例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;
        }
开发者ID:mandreko,项目名称:ADUserCreator,代码行数:32,代码来源:Form1.cs

示例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;
        }
开发者ID:CSPF-Founder,项目名称:RPasswordChanger,代码行数:32,代码来源:PasswordChanger.cs

示例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;
 }
开发者ID:redtchits,项目名称:RCM_NEW,代码行数:14,代码来源:Login.aspx.cs

示例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;
 }
开发者ID:fronn,项目名称:win-net-mon,代码行数:15,代码来源:NetworkBrowser.cs

示例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;
        }
开发者ID:przemo098,项目名称:ccmmanager,代码行数:48,代码来源:ActiveDirectory.cs

示例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;
        }
开发者ID:przemo098,项目名称:ccmmanager,代码行数:47,代码来源:ActiveDirectory.cs

示例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();
            }
        }
开发者ID:fchen,项目名称:dropkick,代码行数:21,代码来源:Iis6Task.cs

示例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;
        }
开发者ID:redtchits,项目名称:RCM_NEW,代码行数:39,代码来源:Login.aspx.cs

示例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();
                }
            }
        }
开发者ID:CSPF-Founder,项目名称:RPasswordChanger,代码行数:39,代码来源:ComputerListRetriever.cs

示例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;
        }
开发者ID:debop,项目名称:NFramework,代码行数:44,代码来源:AdServiceTool.cs

示例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;
            }
        }
开发者ID:chcosta,项目名称:corefx,代码行数:53,代码来源:Context.cs

示例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);
        }
开发者ID:gA-dtech,项目名称:gA-Fest-Website,代码行数:73,代码来源:AccountController.cs


注:本文中的System.DirectoryServices.DirectoryEntry.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。