通过C#从Active Directory获取数据时出现异常

时间:2014-03-20 12:46:24

标签: c# list active-directory directoryservices

我们正在使用foll。用于检索AD用户及其详细信息的代码: -

  

我们得到错误:SearchResultCollection resultCol =   search.FindAll();

     

异常是:DirectoryServiceCOMException:操作错误   发生了。在System.DirectoryServices.DirectoryEntry.Bind(布尔值   throwIfFail)在System.DirectoryServices.DirectoryEntry.Bind()中   在System.DirectoryServices.DirectoryEntry.get_AdsObject()at   System.DirectoryServices.DirectorySearcher.FindAll(布尔   findMoreThanOne)at   SharePointProject20.VisualWebPart1.VisualWebPart1.GetADUsers()

public List<Users> GetADUsers()
        {
            try
            {
                List<Users> lstADUsers = new List<Users>();
                string DomainPath = "LDAP://DC=SYSDOM,DC=local";
                DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
                DirectorySearcher search = new DirectorySearcher(searchRoot);
                search.Filter = "(&(objectClass=user)(objectCategory=person))";
                search.PropertiesToLoad.Add("samaccountname");
                search.PropertiesToLoad.Add("mail");
                search.PropertiesToLoad.Add("usergroup");
                search.PropertiesToLoad.Add("displayname");//first name
                SearchResult result;
                SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    for (int counter = 0; counter < resultCol.Count; counter++)
                    {
                        string UserNameEmailString = string.Empty;
                        result = resultCol[counter];
                        if (result.Properties.Contains("samaccountname") &&
                                 result.Properties.Contains("mail") &&
                            result.Properties.Contains("displayname"))
                        {
                            Users objSurveyUsers = new Users();
                            objSurveyUsers.Email = (String)result.Properties["mail"][0] +
                              "^" + (String)result.Properties["displayname"][0];
                            objSurveyUsers.UserName = (String)result.Properties["samaccountname"][0];
                            objSurveyUsers.DisplayName = (String)result.Properties["displayname"][0];
                            lstADUsers.Add(objSurveyUsers);
                        }
                    }
                }
                return lstADUsers;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


    public class Users
    {
        public string Email { get; set; }
        public string UserName { get; set; }
        public string DisplayName { get; set; }
        public bool isMapped { get; set; }
    }

可能是什么问题?

我们的域名是SYSDOM.local

它是否与权限相关(如何与网络管理员验证?),还是我需要明确传递用户名/密码?

代码参考:http://www.codeproject.com/Tips/599697/Get-list-of-Active-Directory-users-in-Csharp

2 个答案:

答案 0 :(得分:1)

如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。您可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // define a "query-by-example" principal - here, we search for a UserPrincipal 
   UserPrincipal qbeUser = new UserPrincipal(ctx);

   // create your principal searcher passing in the QBE principal    
   PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

   // find all matches
   foreach(var found in srch.FindAll())
   {
       // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
   }
}

如果您还没有 - 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement中的新功能。或者查看MSDN documentation on the System.DirectoryServices.AccountManagement命名空间。

当然,根据您的需要,您可能希望在您创建的“按示例查询”用户主体上指定其他属性:

  • DisplayName(通常:名字+空格+姓氏)
  • SAM Account Name - 您的Windows / AD帐户名称
  • User Principal Name - 您的“username@yourcompany.com”样式名称

您可以在UserPrincipal上指定任何属性,并将其用作PrincipalSearcher的“按示例查询”。

构建示例中显示的PrincipalContext将使用当前用户凭据自动连接到当前AD域。如果需要,可以指定要绑定的其他容器或域,或者也可以使用PrincipalContext构造函数的其他重载提供备用凭据

答案 1 :(得分:0)

在PageLoad中使用HostingEnvironment.Impersonate()后问题得以解决: -

示例:

using (HostingEnvironment.Impersonate()) {
GetADUsers();
}