我想知道用户的电子邮件地址(假设她在典型的Windows办公网络中)。这是在C#应用程序中。
可能会产生影响CurrentUser.EmailAddress;
答案 0 :(得分:111)
参考System.DirectoryServices.AccountManagement
,然后
using System.DirectoryServices.AccountManagement;
UserPrincipal.Current.EmailAddress
或者超时:
var task = Task.Run(() => UserPrincipal.Current.EmailAddress);
if (task.Wait(TimeSpan.FromSeconds(1)))
return task.Result;
答案 1 :(得分:5)
如果您位于Windows域之后,您可以随时从Active Directory中获取其电子邮件地址。
答案 2 :(得分:1)
// Simply by using UserPrincipal
// Include the namespace - System.DirectoryServices
using DS = System.DirectoryServices;
string CurrUsrEMail = string.Empty;
CurrUsrEMail = DS.AccountManagement.UserPrincipal.Current.EmailAddress;
答案 3 :(得分:1)
我不想使用Active Directory选项,而另一个选择最多的答案对我来说效果不佳。
我搜索了代码库,发现它运行良好且响应迅速:
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "[domain]", dc=xx,dc=yyy"))
{
UserPrincipal cp = UserPrincipal.FindByIdentity(ctx, Environment.UserName);
userEmail = cp.EmailAddress;
}
答案 4 :(得分:0)
毫无疑问,很多人都可以使用目录服务(LDAP 等),但是对于那些不能(或愿意)的人来说,这可能是一种替代方法。
PM> Install-Package Microsoft.Office.Interop.Outlook -Version 15.0.4797.1003
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;
}