我正在尝试从活动目录中获取管理器名称,但在引发异常时收到错误“发生操作错误”。
代码如下:
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;
}