📜  C# PrincipalContext 找不到网络路径 - C# (1)

📅  最后修改于: 2023-12-03 14:39:43.816000             🧑  作者: Mango

C# PrincipalContext 找不到网络路径

当使用 C#PrincipalContext 对象进行域控制器连接时,可能会遇到以下错误:

System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.

at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.PropertyValueCollection.PopulateList()
at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
at System.DirectoryServices.PropertyCollection.get_Item(String propertyName)
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer()
at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, String identityValue)
at System.DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)
at ConsoleApp.Program.Main(String[] args) in C:\Users\...\Program.cs:line 16

这个错误通常是由于 PrincipalContext 没有正确指定域控制器引起的。如果域控制器无法识别主机名,则会发生此错误。

以下代码示例中,我们会遇到这个错误:

using System.DirectoryServices.AccountManagement;

class Program
{
    static void Main(string[] args)
    {
        string groupName = "Domain Users";
        using (var context = new PrincipalContext(ContextType.Domain, "wrongServerName.local"))
        {
            using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName))
            {
                // Do something with group
            }
        }
    }
}

解决方法是将 PrincipalContext 构造函数中的服务器名称更改为正确的值:

using System.DirectoryServices.AccountManagement;

class Program
{
    static void Main(string[] args)
    {
        string groupName = "Domain Users";
        using (var context = new PrincipalContext(ContextType.Domain, "correctServerName.local"))
        {
            using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName))
            {
                // Do something with group
            }
        }
    }
}

这样,我们就可以通过 PrincipalContext 成功连接到域控制器并进行操作。