我试图从不同的域获取用户详细信息,但它抛出以下错误:
An exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll but was not handled in user code
代码如下:
// Getting domain
var context = new DirectoryContext(DirectoryContextType.Domain, "alpha");
Domain domain = Domain.GetDomain(context);
using (DirectorySearcher searcher = new DirectorySearcher())
{
var de = new DirectoryEntry(domain.Name);
searcher.SearchRoot = de;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("sAMAccountName");
searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", "myusername");
// *** ERROR HERE ***
var results = searcher.FindAll();
}
我已经尝试过将visual studio作为Domain Admin运行,但没有运气。
提前致谢。
答案 0 :(得分:0)
以下代码仅在使用System.DirectoryServices.ActiveDirectory添加名称空间时才有效,并且还添加引用。
// Get user name
string userName = User.Identity.Name;
var domainName = username.Split('\\')[0];
// Getting domain
var directoryContext = new DirectoryContext(DirectoryContextType.Domain, domainName);
Domain domain = Domain.GetDomain(directoryContext);
using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain.Name))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, userName))
{
if (user != null)
{
// Get details here
var name = user.GivenName;
}
}
}