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


C# DirectorySearcher.FindOne方法代码示例

本文整理汇总了C#中System.DirectoryServices.DirectorySearcher.FindOne方法的典型用法代码示例。如果您正苦于以下问题:C# DirectorySearcher.FindOne方法的具体用法?C# DirectorySearcher.FindOne怎么用?C# DirectorySearcher.FindOne使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.DirectoryServices.DirectorySearcher的用法示例。


在下文中一共展示了DirectorySearcher.FindOne方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: btnLogin_Click

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text.Length == 0 || txtPassword.Text.Length == 0)
            {
                MessageBox.Show("用户名或者密码不能为空。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            string directoryPath = "LDAP://" + GetDomainName();
            string domainAndUsername = directoryPath + txtUserName.Text;

            try
            {
                DirectoryEntry entry = new DirectoryEntry(directoryPath, txtUserName.Text, txtPassword.Text);
                DirectorySearcher search = new DirectorySearcher(entry);

                SearchResult result = search.FindOne();
                MessageBox.Show("登录成功。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // 如果用户名或者密码不正确,也会抛出异常。
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
开发者ID:cbfjay,项目名称:Aspnet.Login,代码行数:25,代码来源:Form1.cs

示例2: GetUserImage

        public BitmapImage GetUserImage(string userName)
        {
            using (DirectorySearcher dsSearcher = new DirectorySearcher(this.entry))
            {
                dsSearcher.Filter = "(&(objectClass=user) (cn=" + userName.Split('\\').Last() + "*))";
                SearchResult result = dsSearcher.FindOne();

                if (result == null)
                    return null;

                using (DirectoryEntry user = new DirectoryEntry(result.Path))
                {
                    byte[] data = user.Properties[this.imageProperty].Value as byte[];

                    if (data == null)
                        return null;

                    using (var stream = new MemoryStream(data))
                    {
                        BitmapImage image = new BitmapImage();

                        image.BeginInit();
                        image.StreamSource = stream;
                        image.EndInit();

                        return image;
                    }
                }
            }
        }
开发者ID:peschuster,项目名称:tfs-statistics,代码行数:30,代码来源:DirectoryUserImageService.cs

示例3: ChangePassword

 /// <summary>
 /// �������û�������
 /// </summary>
 /// <param name="UserName">���û���</param>
 /// <param name="OldPassword">������</param>
 /// <param name="NewPassword">������</param>
 /// <param name="DomainName">DNS����</param>
 /// <returns>�ɹ������棬���ɹ����ؼ�</returns>
 public static bool ChangePassword(string UserName, string OldPassword, string NewPassword, string DomainName)
 {
     try
     {
         string UserPrincipalName = UserName + "@" + DomainName;
         DirectoryEntry deRootDSE = new DirectoryEntry("LDAP://RootDSE", UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
         DirectoryEntry deDomain = new DirectoryEntry("LDAP://" + deRootDSE.Properties["defaultNamingContext"].Value.ToString(), UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
         DirectorySearcher dsSearcher = new DirectorySearcher();
         dsSearcher.SearchRoot = deDomain;
         dsSearcher.SearchScope = SearchScope.Subtree;
         dsSearcher.Filter = "(userPrincipalName=" + UserPrincipalName + ")";
         SearchResult srResult = dsSearcher.FindOne();
         if (srResult != null)
         {
             DirectoryEntry deUser = new DirectoryEntry(srResult.GetDirectoryEntry().Path, UserPrincipalName, OldPassword, AuthenticationTypes.Secure);
             deUser.Invoke("ChangePassword", new object[] { OldPassword, NewPassword });
             deUser.CommitChanges();
             return true;
         }
         else
             return false;
     }
     catch //(Exception ex)
     {
         return false;// ex.Message;
     }
 }
开发者ID:songques,项目名称:CSSIM_Solution,代码行数:35,代码来源:DNS.cs

示例4: GetDirectoryObjectById

		public override DirectoryObject GetDirectoryObjectById(string id) {
			if(id == null) {
				throw new ArgumentNullException("id");
			}
			DirectoryObject directoryObject = null;
			if(id.Length > 0) {
				using(DirectoryEntry directoryEntry = this.GetDirectoryEntry()) {
					using(DirectorySearcher directorySearcher = new DirectorySearcher(
							  directoryEntry,
							  string.Format(CultureInfo.InvariantCulture, FilterAndFormat, BaseFilter + string.Format(CultureInfo.InvariantCulture, FilterFormat, this.IdentifyingPropertyName, id)),
							  PropertyNames,
							  SearchScope.Subtree)) {
						SearchResult searchResult = directorySearcher.FindOne();
						if(searchResult != null) {
							directoryObject = this.CreateDirectoryObjectInstance();
							directoryObject.Id = GetPropertyValue(searchResult, this.IdentifyingPropertyName);
							foreach(string propertyName in searchResult.Properties.PropertyNames) {
								if(directoryObject.Contains(propertyName)) {
									directoryObject[propertyName] = GetPropertyValue(searchResult, propertyName);
								}
							}
						}
					}
				}
			}
			return directoryObject;
		}
开发者ID:aelveborn,项目名称:njupiter,代码行数:27,代码来源:LdapDirectoryService.cs

示例5: getGrups

        static public void getGrups(string username, string group_Admin)
        {
            try
            {
                //   string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", "afanasievdv");
                string domain = "isea.ru";
                string[] properties = new string[] { "fullname" };
              //  username = "afanasievdv";

                DirectoryEntry adRoot = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure);
                DirectorySearcher dirsearcher = new DirectorySearcher(adRoot);
                dirsearcher.Filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", username);
                dirsearcher.PropertiesToLoad.Add("memberOf");
                int propCount;

                SearchResult dirSearchResults = dirsearcher.FindOne();
                propCount = dirSearchResults.Properties["memberOf"].Count;

                DirectoryEntry directoryEntry = dirSearchResults.GetDirectoryEntry();
                //  string dn, equalsIndex, commaIndex;
                PropertyValueCollection groups = directoryEntry.Properties["memberOf"];
                foreach (string g in groups)
                {
                    string group = g.Split('=')[1].Split(',')[0];
                    System.Diagnostics.Debug.WriteLine(group);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
开发者ID:svfits,项目名称:reg_calim,代码行数:32,代码来源:AD.cs

示例6: ValidarUsuarioActiveDirectory

 //- Método que valida el usuario en el Active Directory
 public bool ValidarUsuarioActiveDirectory(string _Path, string userId, string password)
 {
     DirectoryEntry deEntry = new DirectoryEntry(_Path, userId, password);
     DirectorySearcher dsSearcher = new DirectorySearcher(deEntry);
     bool bandera = false;
     try
     {
         UsuarioId(userId);
         dsSearcher.Filter = "(SAMAccountName=" + w_UserAD.Trim() + ")";
         dsSearcher.PropertiesToLoad.Add("cn");
         SearchResult result = dsSearcher.FindOne();
         if (!string.IsNullOrEmpty(result.ToString()))
         {
             bandera = true;
         }
         else
         {
             bandera = false;
         }
         _path = result.Path;
         _filterAttribute = (String)result.Properties["cn"][0];
     }
     catch (Exception)
     {
         return false;
     }
     return bandera;
 }
开发者ID:WilliamMorales1989,项目名称:sgrweb,代码行数:29,代码来源:MetodosOperacion.cs

示例7: GetGroups

        // potentially not needed due to use of the role provider
        public string GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                string dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (string)result.Properties["memberOf"][propertyCounter];
                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }
开发者ID:dohrte,项目名称:CapstoneProject,代码行数:34,代码来源:LdapAuthentication.cs

示例8: Initialize

        private void Initialize()
        {
            this.Name = Domain.Name;

            var dc = Domain.FindDomainController();

            string ldapPath = string.Format("LDAP://{0}/", dc.Name);

            using (var adRootDSE = new DirectoryEntry(ldapPath + "RootDSE"))
            {
                this.DistinguishedName = adRootDSE.Properties["defaultNamingContext"][0].ToString();
                this.ConfigurationNamingContext = adRootDSE.Properties["configurationNamingContext"][0].ToString();
            }

            using (var adDomainRoot = new DirectoryEntry(ldapPath + this.DistinguishedName))
            {
                this.SecurityIdentifier = new SecurityIdentifier((byte[])(adDomainRoot.Properties["objectSid"][0]), 0);
            }

            using (var configSearchRoot = new DirectoryEntry(ldapPath + "CN=Partitions," + this.ConfigurationNamingContext))
            {
                var configSearchFilter = string.Format("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", this.Name);

                using (var configSearcher = new DirectorySearcher(configSearchRoot, configSearchFilter, new string[] { "NetBIOSName" }, System.DirectoryServices.SearchScope.OneLevel))
                {
                    SearchResult configResult = configSearcher.FindOne();
                    if (configResult != null)
                        this.NetBiosName = configResult.Properties["NetBIOSName"][0].ToString();
                    else
                        this.NetBiosName = null;
                }
            }
        }
开发者ID:garysharp,项目名称:Disco,代码行数:33,代码来源:ADDomain.cs

示例9: GetPrimarySmtp

        /// <summary>
        /// Get the primary SMTP address of the given user name
        /// </summary>
        /// <param name="upnUserName">UPN formatted user name to look up</param>
        /// <returns>Primary SMTP address of the user if found</returns>
        public static string GetPrimarySmtp(string upnUserName)
        {
            string primarySmtp = string.Empty;

            // Use the current user's identity to get their
            // default SMTP address from the default domain.
            // In other words - make a lot of assumptions!

            // This logic is very thin but maybe it will stand up...
            // Expecting the format of the identity to be
            // 'DomainName\sAMAccountName', if not BOOM!
            if (!upnUserName.Contains("\\"))
            {
                throw new ApplicationException("Unknown identity name pattern, cannot retrieve default SMTP address.");
            }

            // Tear off the sAMAccountName from the identity string
            string sAMAccountName = upnUserName.Split(new char[] { '\\' })[1];

            // Search AD for the sAMAccountName
            DirectorySearcher ds = new DirectorySearcher();
            ds.Filter = string.Format(System.Globalization.CultureInfo.CurrentCulture, "sAMAccountName={0}", sAMAccountName);

            SearchResult result = ds.FindOne();

            if (result == null)
            {
                // If there are no results go BOOM!
                throw new ApplicationException("Directory entry not found, cannot retrieve default SMTP address.");
            }

            // Get the 'mail' property and assume the
            // first value is the primary SMTP address
            return result.Properties["mail"][0].ToString();
        }
开发者ID:haiyangIt,项目名称:Haiyang,代码行数:40,代码来源:ActiveDirectoryHelper.cs

示例10: AuthenticateUser

        public User AuthenticateUser(string username, string password)
        {
            try
            {
                DirectoryEntry deSystem = new DirectoryEntry();
                deSystem.AuthenticationType = AuthenticationTypes.Secure;
                deSystem.Username = username;
                deSystem.Password = password;

                // Bind to the native AdsObject to force authentication.
                Object obj = deSystem.NativeObject;
                DirectorySearcher ds = new DirectorySearcher(deSystem);
                ds.Filter = "(SAMAccountName=" + username + ")";
                ds.PropertiesToLoad.Add("name");
                ds.PropertiesToLoad.Add("mail");

                SearchResult sr = ds.FindOne();
                if (sr == null)
                {
                    return null;
                }

                DirectoryEntry de = sr.GetDirectoryEntry();
                User user = new User();
                user.UserId = username;
                user.UserName = de.Properties["name"].Value.ToString();
                user.Email = de.Properties["mail"].Value.ToString();
                return user;
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                return null;
            }
        }
开发者ID:Soucre,项目名称:Working_git_vfs,代码行数:35,代码来源:ActiveDirectoryResourceService.cs

示例11: GetUserPicture

        public Image GetUserPicture(string userName, string domain)
        {
            var directoryEntry = new DirectoryEntry("LDAP://" + domain);
            var propertiesToLoad = new[] { "thumbnailPhoto", "samaccountname" };
            var filter = $"(&(SAMAccountName={userName}))";
            var directorySearcher = new DirectorySearcher(directoryEntry, filter, propertiesToLoad);
            var user = directorySearcher.FindOne();

            if (user == null)
            {
                _log.Warn($"Could not find user '{userName}' in active directory");
                return null;
            }

            if (!user.Properties.Contains("thumbnailPhoto"))
            {
                var message = "LDAP did not contain a thumbnailPhoto property for " + userName;
                _log.Warn(message);
                return null;
            }
            var bytes = user.Properties["thumbnailPhoto"][0] as byte[];
            if (bytes == null) return null;
            using (var ms = new MemoryStream(bytes))
            {
                var image = Image.FromStream(ms);
                return image;
            }
        }
开发者ID:AutomatedArchitecture,项目名称:SirenOfShame,代码行数:28,代码来源:ActiveDirectoryService.cs

示例12: AutenticarEnDominio

        private static bool AutenticarEnDominio(string userDisplayName, string codigoUsuario, string password)
        {
            ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            DirectoryEntry entry = GetDirectoryEntry();
            entry.Username = codigoUsuario;
            entry.Password = password;

            try
            {
                var ds = new DirectorySearcher(entry)
                {
                    Filter = ("(&(objectclass=user)(objectcategory=person)(displayname=" + userDisplayName + "))")
                };
                ds.SearchScope = SearchScope.Subtree;
                SearchResult results = ds.FindOne();

                if (results != null)
                {
                    return true;
                }

                entry.Close();
                return false;
            }
            catch (Exception ex)
            {
                Logger.Error("Exception AutenticarEnDominio:" + ex.Message);
                return false;
            }
        }
开发者ID:MijailStell,项目名称:Falabella,代码行数:31,代码来源:Program.cs

示例13: GetKUsr

        public static KUsr GetKUsr(string userId)
        {
            var kUsr = new KUsr();

            if (string.IsNullOrWhiteSpace(userId))
                return kUsr;

            kUsr.UserId = userId;//AmUtil.GetCurrentUser;

            SearchResult result = null;

            using (DirectoryEntry AdEntry = ConfigUtility.IsAdTLogin() ?
                new DirectoryEntry(ConfigUtility.GetActiveDirectory()) :
                new DirectoryEntry(ConfigUtility.GetActiveDirectory(), ConfigUtility.GetAdLoginInfo().Item1, ConfigUtility.GetAdLoginInfo().Item2))
            {
                using (DirectorySearcher AdSearcher = new DirectorySearcher(AdEntry))
                {
                    AdSearcher.Filter = "(CN=" + kUsr.UserId + ")";
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name);
                    //AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name);
                    AdSearcher.PropertiesToLoad.Add(kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name);

                    result = AdSearcher.FindOne();
                }

                //AdEntry.Close();
            }

            if (result != null)
            {
                DirectoryEntry usrEntry = result.GetDirectoryEntry();

                kUsr.Domain = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Domain).Name].Value.ToString();

                kUsr.FName = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.FName).Name].Value.ToString();

                kUsr.LName = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.LName).Name].Value.ToString();

                kUsr.EmailId = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.EmailId).Name].Value.ToString();

                //kUsr.UserInitials = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name].Value == null ? null :
                //    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.UserInitials).Name].Value.ToString();

                kUsr.Location = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Location).Name].Value.ToString();

                kUsr.Department = usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name].Value == null ? null :
                    usrEntry.Properties[kUsr.GetPropAttr<KUsr, AltPropName>(x => x.Department).Name].Value.ToString();
            }

            return kUsr;
        }
开发者ID:vivekatgithub,项目名称:XP-1,代码行数:60,代码来源:AmUtility.cs

示例14: GetSearchResult

 public static SearchResult GetSearchResult(string user, string password, string LDAPPath)
 {
     SearchResult sRsResult = null;
     DirectoryEntry entry = null;
     DirectorySearcher mySearcher = null;
     entry = GetDirectoryEntry(user, password, LDAPPath);
     if (entry != null)
     {
         try
         {
             mySearcher = new DirectorySearcher(entry);
         }
         catch (COMException) { };
         if (mySearcher != null)
         {
             try
             {
                 string strFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + user + "))";
                 mySearcher.Filter = strFilter;
                 sRsResult = mySearcher.FindOne();
             }
             catch (COMException) { };
         }
         else { };
     }
     else { };
     return sRsResult;
 }
开发者ID:khanhdtn,项目名称:my-fw-win,代码行数:28,代码来源:HelpLDAP.cs

示例15: FindUser

        public static DirectoryEntry FindUser(string userName)
        {
            if (string.IsNullOrEmpty(LoginDomain) || !UseWindowsCreds && (string.IsNullOrEmpty(DomainName) || string.IsNullOrEmpty(Username) || string.IsNullOrEmpty(Password)))
            {
                if (EditADPrefs.Execute() != System.Windows.Forms.DialogResult.OK)
                    return null;
            }

            try
            {
                DirectoryEntry dom = null;
                if (UseWindowsCreds)
                    dom = new DirectoryEntry("LDAP://" + DomainName);
                else
                    dom = new DirectoryEntry("LDAP://" + DomainName, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
                using (DirectorySearcher dsSearcher = new DirectorySearcher(dom))
                {
                    dsSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(samaccountname={0})))", userName);
                    dsSearcher.PropertiesToLoad.Add("ThumbnailPhoto");
                    SearchResult result = dsSearcher.FindOne();

                    if (result == null || string.IsNullOrEmpty(result.Path))
                        return null;

                    if (UseWindowsCreds)
                        return new DirectoryEntry(result.Path);
                    return new DirectoryEntry(result.Path, LoginDomain + @"\" + Username, Password, AuthenticationTypes.None);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("Failed to search for user.\r\n\r\nError was:\r\n{0}", e.Message), "A/D Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return null;
        }
开发者ID:Corey-M,项目名称:Misc,代码行数:35,代码来源:AD.cs


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