我试图从活动目录获取管理器名称,但在引发异常时收到错误“An operation error occured”。尝试从活动目录中检索数据时发生操作错误
代码如下:
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;
}
'Properties'是你需要转换,对于初学者 '字符串managerName =(字符串)dir.Properties对象[“Manager”]。Value.ToString();'你怎么知道当你在catch中没有代码的时候真正的错误是什么'var message = ex.Message;'你能发布完整的代码吗?方法也使用调试器,并通过每一行验证您确实具有有效的数据/值。 – MethodMan 2013-03-21 17:05:51
当我调试时逐步完成时,我会看到异常处于捕获状态时的情况。我会尝试一下你的建议 – 2013-03-21 17:06:36
只试图帮助Ryan我知道AD很好,而我所看到的看起来像是在你的LDAP中缺少了一些东西://你的conn中缺少'389'地址字符串 – MethodMan 2013-03-21 17:07:15