vb.net 从 Active Directory 获取电子邮件地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15913271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting Email address from Active Directory
提问by Mark Kram
All --
全部 -
I am able to retieve the FullName value I am trying to retrieve an email address from Active Directory but using the following code in my ASP.Net Web Forms project that is using Windows Authentication:
我能够检索 FullName 值我正在尝试从 Active Directory 检索电子邮件地址,但在使用 Windows 身份验证的 ASP.Net Web 窗体项目中使用以下代码:
Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')
Dim ADEntry As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry(Convert.ToString("WinNT://" + a(0) + "/" + a(1)))
Dim Name As String = ADEntry.Properties("FullName").Value.ToString()
Dim Email As String = ADEntry.Properties("mail").Value.ToString()
when I get to the line of code where I'm try to retrieve the email address I get an "Object reference not set to an instance of an object." error. I have tried using EmailAddress, E-Mail. I think the problem is that I am simply using the wrong keyword. I am able to retrieve the FullName value.
当我到达尝试检索电子邮件地址的代码行时,我收到“对象引用未设置为对象的实例”。错误。我曾尝试使用电子邮件地址、电子邮件。我认为问题在于我只是使用了错误的关键字。我能够检索 FullName 值。
回答by Mark Kram
Thanks to Davide Piraswho send me this link, I found a suitable solution:
感谢Davide Piras给我发送了这个链接,我找到了一个合适的解决方案:
Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')
Dim dc As PrincipalContext = New PrincipalContext(ContextType.Domain, "DomainName")
Dim adUser As UserPrincipal = UserPrincipal.FindByIdentity(dc, a(1))
Dim Email As String = adUser.EmailAddress
回答by A Ghazal
This code works for me..
Reference to System.DirectoryServices.AccountManagement
这段代码对我有用..参考 System.DirectoryServices.AccountManagement
static string GetADUserEmailAddress(string username)
{
using (var pctx = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal up = UserPrincipal.FindByIdentity(pctx, username))
{
return up != null && !String.IsNullOrEmpty(up.EmailAddress) ? up.EmailAddress : string.Empty;
}
}
}
to use it:
使用它:
lblEmail.Text = GetADUserEmailAddress(Request.ServerVariables["AUTH_USER"]);

