【问题标题】:DirectoryEntry does not contain a definition for 'Properties' (.NET CORE 3.1)DirectoryEntry 不包含“属性”的定义(.NET CORE 3.1)
【发布时间】:2020-05-07 14:06:19
【问题描述】:

我正在尝试从 AD 获取特定用户的部门属性。但它说DirectoryEntry does not contain a definition for 'Properties'。 stackoverflow 上的很多示例都使用以下代码。为什么这对我不起作用,我执行错了吗?我正在使用 .net 核心 3.1。

var user = UserPrincipal.FindByIdentity(ctx, domainUser.DistinguishedName);
DirectoryEntry dirEntry = (DirectoryEntry)user.GetUnderlyingObject();                        
string dept = dirEntry.Properties["Department"].Value.ToString();

我正在使用以下(相关)导入。

using System.DirectoryServices.AccountManagement;
using System.Reflection.PortableExecutable;

【问题讨论】:

    标签: c# .net .net-core active-directory


    【解决方案1】:

    我自己修好了。原来你必须在nuget中安装System.DirectoryServices。安装后我做了:

    using System.DirectoryServices;
    

    System.Reflection.PortableExecutable 导入错误...

    【讨论】:

      【解决方案2】:

      如您所见,这是因为System.Reflection.PortableExecutable 有一个DirectoryEntry 的定义,而您确实想使用System.DirectoryServices.DirectoryEntry

      但另一个注意事项:department 属性不是必需的。如果它是空的,Value 将是null 并且对ToString() 的调用将引发异常。所以你最好改用string

      var dept = (string) dirEntry.Properties["department"].Value;
      

      这样,如果department 没有值,您的dept 变量将只是以null 结束,而不是引发异常。

      【讨论】:

      • 是的,我遇到过空指针异常...感谢您的补充说明!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2019-04-04
      相关资源
      最近更新 更多