尝试从活动目录中检索数据时发生操作错误

时间:2013-03-21 17:03:04

标签: c# sharepoint-2010 active-directory

我试图从活动目录中获取管理员名称但是收到错误"发生了操作错误"当它抛出异常。

代码如下:

public override void ItemAdding(SPItemEventProperties properties)
{
   base.ItemAdding(properties);

   try 
   {
      var requester = properties.Web.CurrentUser;

      properties.AfterProperties["Requester"] = requester;

      //Get the manager name from the active directory
      var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
   DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain);
      //Exeception occurs on this line below.
      string managerName = dir.Properties["Manager"].Value.ToString();

      properties.AfterProperties["Manager"] = managerName;

   }
   catch(Exception ex)
   {

   }
}

修改 能够使用下面的代码解决这个问题:

try
    {
        // set up domain context
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

        // find a user
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
        string samAccountName = "";


        if (user != null)
        {
            // do something here....     
            samAccountName = user.SamAccountName;
        }


        //Get the manager name from the active directory
        var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

        using(DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain))
        {
            using (DirectorySearcher ds = new DirectorySearcher(dir, "samAccountName=" + samAccountName))
            {

                SearchResult result = ds.FindOne();

                string managerName = result.Properties["manager"][0].ToString();
            }
        }


    }
    catch (Exception ex)
    {
        var message = ex.Message;
    }

1 个答案:

答案 0 :(得分:1)

您正尝试从域访问Manager,而不是从请求者访问。

在winform中我会这样做,假设请求者== samAccountName:

       try
        {

            //Get the manager name from the active directory
            var domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
            using (DirectoryEntry dir = new DirectoryEntry("LDAP://" + domain))
            {
                using (DirectorySearcher ds = new DirectorySearcher(dir, "samAccountName=" + requster))
                {
                    SearchResult sr = ds.FindOne();
                    //Exeception occurs on this line below, if the attribute is not set.
                    string managerName = sr.Properties["Manager"][0].ToString();
                }
            }

        }
        catch (Exception ex)
        {

        }