如何从Active Directory检索用户的登录名?

时间:2011-03-17 10:20:34

标签: c# asp.net active-directory

我想从Active Directory中检索用户的登录名。

例如,名字是'Jan Van der Linden' 在将此名称作为参数后,我必须获取其登录名作为回报,例如jvdlinden

5 个答案:

答案 0 :(得分:6)

由于您使用的是.NET 3.5及更高版本,因此您应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读所有相关内容:

Managing Directory Security Principals in the .NET Framework 3.5

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

public string GetLoginName(string userName)
{
  // set up domain context
  PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

  // find user by name
  UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName);

  if(user != null)
       return user.SamAccountName;
  else
       return string.Empty;
}

新的S.DS.AM使得在AD中使用用户和群组变得非常容易:

答案 1 :(得分:1)

使用.net库,您可以使用以下代码从活动目录中获取用户名或任何信息

using System.Management;
using System.Management.Instrumentation;
using System.Runtime.InteropServices;
using System.DirectoryServices;

ManagementObjectSearcher Usersearcher = new ManagementObjectSearcher("Select * From Win32_ComputerSystem Where (Name LIKE 'ws%' or Name LIKE 'it%')"); 
            ManagementObjectCollection Usercollection = Usersearcher.Get(); 
            string[] sep = { "\\" };
            string[] UserNameDomain = Usercollection.Cast<ManagementBaseObject>().First()["UserName"].ToString().Split(sep, StringSplitOptions.None);

我添加“Select * From Win32_ComputerSystem Where(Name LIKE'ws%'或Name LIKE'it%')” 这将以全名

获取用户名

希望这可以帮到你

答案 2 :(得分:1)

这实际上几乎完全相反,但可以根据需要检查和修改起点:

Finding a User in Active Directory with the Login Name

答案 3 :(得分:1)

检查此链接是否需要代码snipple

Validate AD-LDAP USer

using (DirectoryEntry entry = new DirectoryEntry())
        {
            entry.Username = "DOMAIN\\LOGINNAME";
            entry.Password = "PASSWORD";
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = "(objectclass=user)";
            try
            {
                searcher.FindOne();
                {
                    //Add Your Code if user Found..
                }
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == -2147023570)
                {
                    ex.Message.ToString();
                    // Login or password is incorrect 
                }
            }
        }

答案 4 :(得分:0)

没有身份:

private string GetLogonFromDisplayName(string displayName)
{
    var search = new DirectorySearcher(string.Format("(&(displayname={0})(objectCategory=user))", displayName));
    search.PropertiesToLoad.Add("sAMAccountName");

    SearchResult result = search.FindOne();
    if (result != null)
    {
        var logonNameResults = result.Properties["sAMAccountName"];
        if (logonNameResults == null || logonNameResults.Count == 0)
        {
            return null;
        }

        return logonNameResults[0].ToString();
    }

    return null;
}