【问题标题】:Principal does not contain a definition for 'EmailAddress'主体不包含“电子邮件地址”的定义
【发布时间】:2020-11-04 18:11:19
【问题描述】:

我正在尝试通过 Windows 服务应用从 Windows 2016 服务上的 OU 检索用户(以将帐户同步到另一个服务)。

我有下面的代码来搜索 OU,然后将结果添加到列表中。

List<string> UserList = new List<string>();

PrincipalContext context = new PrincipalContext(ContextType.Domain, domain, OU);
UserPrincipal userqbe = new UserPrincipal(context);
PrincipalSearcher searcher = new PrincipalSearcher(userqbe);

foreach (var found in searcher.FindAll())
{
    UserList.Add(found.EmailAddress);
}

我收到以下错误:

'Principal' 不包含 'EmailAddress' [...] 的定义(您是否缺少 using 指令或程序集引用?)

在那次错误之后,我引用了所需的程序集:

  • System.DirectoryServices
  • System.DirectoryServices.AccountManagent

并将它们包含在我的代码中:

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

关于用户原则类的microsoft documentation 确实显示了EmailAddress 属性。 DisplayName 等其他属性可以正常工作。

我在这里错过了什么?

【问题讨论】:

  • foreach (var found in searcher.FindAll().OfType&lt;UserPrincipal&gt;())?
  • 拼写很重要。 “校长”!=“原则”。 EmailAddress 属性有两个 D,而您的问题标题 EmailAdress 缺少一个。
  • 所以要么你的问题是“错别字”,要么你没有显示实际的错误信息。
  • @stuartd 解决了这个问题,添加它作为答案,我会接受它。

标签: c# windows-services directoryservices


【解决方案1】:

在此处查看FindAll 文档:https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.principalsearcher.findall?view=dotnet-plat-ext-3.1#System_DirectoryServices_AccountManagement_PrincipalSearcher_FindAll

返回

PrincipalSearchResult<Principal>

所以,只需投射你找到的对象

UserList.Add(((UserPrincipal)found).EmailAddress);

请注意,如果您不确定主体类型,这很危险。为避免任何运行时错误,您可以使用 Is 运算符 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is

【讨论】:

    猜你喜欢
    • 2020-12-25
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2019-03-31
    相关资源
    最近更新 更多