要获取活动目录中用户的完整路径,可以使用System.DirectoryServices.AccountManagement命名空间中的PrincipalContext类。以下是示例代码:
using System.DirectoryServices.AccountManagement;
public string GetUserFullPath(string userName)
{
using(var context = new PrincipalContext(ContextType.Domain))
{
var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
if(user != null)
{
return user.DistinguishedName;
}
return null;
}
}
在此示例中,我们使用UserPrincipal.FindByIdentity方法查找用户名对应的UserPrincipal对象。然后,我们可以访问UserPrincipal对象的DistinguishedName属性来获取用户的完整路径。
请注意,必须使用正确配置的PrincipalContext对象才能访问活动目录。如果默认的构造函数未能正常运行,可以尝试使用指定域名称的构造函数:
new PrincipalContext(ContextType.Domain, "mydomain.com")
这将使用指定的域名来配置PrincipalContext对象。请根据实际情况进行调整。