Get current user's email address in .NET

孤街醉人 提交于 2019-12-20 09:57:25

问题


I would like to know the email address of the user (assuming she's in a typical Windows office network). This is in a C# application. Perhaps something to the effect of

CurrentUser.EmailAddress; 

回答1:


If you're behind a Windows domain, you could always grab their email address out of Active Directory.

Here's an example: http://lozanotek.com/blog/articles/149.aspx




回答2:


Reference System.DirectoryServices.AccountManagement, then

using System.DirectoryServices.AccountManagement;
UserPrincipal.Current.EmailAddress

Or with a timeout:

var task = Task.Run(() => UserPrincipal.Current.EmailAddress);
if (task.Wait(TimeSpan.FromSeconds(1)))
    return task.Result;



回答3:


// Simply by using UserPrincipal
// Include the namespace - System.DirectoryServices

using DS = System.DirectoryServices;
string CurrUsrEMail = string.Empty;
CurrUsrEMail = DS.AccountManagement.UserPrincipal.Current.EmailAddress;



回答4:


I didn't want to use the Active Directory option and the other, most selected answer, did not work for me oddly enough.

I searched my code bank and found this which worked fine and with quick response:

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "[domain]",  dc=xx,dc=yyy"))
{
    UserPrincipal cp = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
    userEmail = cp.EmailAddress;
}


来源:https://stackoverflow.com/questions/7357123/get-current-users-email-address-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!