我想知道用户的电子邮件地址(假设她在典型的Windows办公网络中)。这是一个C#应用程序。也许类似于以下内容:
CurrentUser.EmailAddress;
我想知道用户的电子邮件地址(假设她在典型的Windows办公网络中)。这是一个C#应用程序。也许类似于以下内容:
CurrentUser.EmailAddress;
参考 System.DirectoryServices.AccountManagement
,然后
using System.DirectoryServices.AccountManagement;
return UserPrincipal.Current.EmailAddress;
参见.NET文档中的UserPrincipal.Current和UserPrincipal.EmailAddress。
或使用超时:
var task = Task.Run(() => UserPrincipal.Current.EmailAddress);
if (task.Wait(TimeSpan.FromSeconds(1)))
return task.Result;
如果您在Windows域中,请从Active Directory中获取他们的电子邮件地址。
请参阅Javier G. Lozano在他的教程“查询用户电子邮件的Active Directory”中的示例。
// Simply by using UserPrincipal
// Include the namespace - System.DirectoryServices
using DS = System.DirectoryServices;
string CurrUsrEMail = string.Empty;
CurrUsrEMail = DS.AccountManagement.UserPrincipal.Current.EmailAddress;
我不想使用Active Directory选项,而且其他最常选的答案对我来说奇怪地不起作用。
我搜索了我的代码库,并找到了这个可以很好地快速响应的解决方案:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "[domain]", dc=xx,dc=yyy"))
{
UserPrincipal cp = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
userEmail = cp.EmailAddress;
}
using MSOutlook = Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;
...
private async Task<string> GetCurrentUserEmailAsync()
{
var value = string.Empty;
MSOutlook.Application outlook = new MSOutlook.Application();
await Task.Delay(3000);
MSOutlook.AddressEntry addrEntry =
outlook.Session.CurrentUser.AddressEntry;
if (addrEntry.Type == "EX")
{
MSOutlook.ExchangeUser currentUser =
outlook.Session.CurrentUser.
AddressEntry.GetExchangeUser();
if (currentUser != null)
{
value = currentUser.PrimarySmtpAddress;
}
Marshal.ReleaseComObject(currentUser);
}
Marshal.ReleaseComObject(addrEntry);
Marshal.ReleaseComObject(outlook);
return value;
}