C#报”ActiveDirectoryObjectNotFoundException”的原因以及解决办法

  • Post category:C#

针对.Net报”ActiveDirectoryObjectNotFoundException”的问题,我做如下解释和演示。

问题原因

这个异常表示在Active Directory中找不到所请求的对象。这可能是由于以下一些原因导致的:

  • 指定的路径无效
  • 指定路径的对象不存在
  • 没有足够的权限来访问路径中的对象

解决办法

为了解决”ActiveDirectoryObjectNotFoundException”,可考虑如下两种办法:

1. 确认指定路径是否正确及对象是否存在

首先,需要确认代码中指定的路径是否正确,要注意大小写和拼写是否一致。其次,需要确认代码中请求的对象在该路径下是否真实存在。

示例代码1:

string path = "LDAP://CN=Users,DC=example,DC=com";
DirectoryEntry directoryEntry = new DirectoryEntry(path);

try
{
    DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
    searcher.Filter = "(&(objectCategory=person)(objectClass=user))";
    SearchResult result = searcher.FindOne();

    if (result != null)
    {
        Console.WriteLine("Found User: " + result.Path);
    }
    else
    {
        Console.WriteLine("User not Found");
    }
}
catch (ActiveDirectoryObjectNotFoundException ex)
{
    Console.WriteLine(ex.Message);
}

在上述示例代码中,我们在LDAP路径下查找用户对象,并捕获了ActiveDirectoryObjectNotFoundException异常。异常信息将在控制台输出。

2. 给当前身份添加足够的权限

如果确认代码中的路径和对象都正确存在,还可以考虑是否给当前身份添加了足够的权限来访问路径中的对象。要访问Active Directory,需要使用Windows凭据来执行。如果没有足够的权限,将会引发”ActiveDirectoryObjectNotFoundException”异常。

示例代码2:

string path = "LDAP://CN=Users,DC=example,DC=com";
DirectoryEntry directoryEntry = new DirectoryEntry(path, "username", "password");

try
{
    DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
    searcher.Filter = "(&(objectCategory=person)(objectClass=user))";
    SearchResult result = searcher.FindOne();

    if (result != null)
    {
        Console.WriteLine("Found User: " + result.Path);
    }
    else
    {
        Console.WriteLine("User not Found");
    }
}
catch (ActiveDirectoryObjectNotFoundException ex)
{
    Console.WriteLine(ex.Message);
}

在上述示例代码中,我们使用给定的凭据来访问Active Directory,可以查看是否能够成功找到请求的对象。

总之,对于”ActiveDirectoryObjectNotFoundException”异常,需要仔细检查路径和对象是否存在,以及当前身份是否具有足够的权限进行访问。