在.NET中获取当前用户的电子邮件地址

45

我想知道用户的电子邮件地址(假设她在典型的Windows办公网络中)。这是一个C#应用程序。也许类似于以下内容:

CurrentUser.EmailAddress; 

请澄清您的问题。您是通过某种API扩展Exchange服务器吗?这是一个独立的应用程序,连接到Exchange并尝试找出何时满足“特定条件”吗?您在这里没有给我们太多可以使用的信息。 - feathj
我非常确定OP在谈论AD。然而,Calv1n,你应该通过编辑来澄清你的问题,否则社区可能会关闭它。 - Tim Post
5个回答

141

参考 System.DirectoryServices.AccountManagement,然后

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

参见.NET文档中的UserPrincipal.CurrentUserPrincipal.EmailAddress


或使用超时:

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

11
这应该是被接受的答案。比链接的文章简单得多。 - Matt Honeycutt
1
UserPrincipal.Current 在我的非域计算机上非常缓慢。似乎在该属性返回之前有大约5秒的超时,我还没有找到解决方法。 - angularsen
1
重要提示:如果用户不在域上,这将非常缓慢。这是您的客户会看到而不是您自己的问题之一。 - Robin
此外 - 非域计算机会收到“文件未找到”的异常。 - David Ford
UserPrincipal.Current在.NET上不起作用,即使在Windows操作系统上也会抛出PlatformNotSupportedException异常。它只适用于.NET Framework;请参阅文档:https://learn.microsoft.com/en-us/dotnet/api/system.directoryservices.accountmanagement.userprincipal.current?view=netframework-4.8 - daniol

5

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

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

2
虽然这可能回答了作者的问题,但它缺少一些解释性的词语和文档链接。裸代码片段没有周围的一些短语是不太有帮助的。请编辑您的答案。 - hellow

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;
}

3
那是LDAP,它是Active Directory。 - Fandango68

0
毫无疑问,许多人都可以使用目录服务(LDAP等),但对于那些无法或不愿意使用它的人来说,这可能是一种替代方法。 < p > < code > 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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接