获取有关在 VSTO AddIn 中登录 Office 应用程序的 LiveId (Office 365) 帐户的信息

Get information about LiveId (Office 365) account logged in Office application in VSTO AddIn

我为 Word、Excel 等开发 VSTO 加载项。 我需要获取有关当前登录 Office 应用程序的用户的信息。 我至少需要一个电子邮件地址。

我找到了这些属性 Globals.ThisAddIn.Application.UserName.UserInitials.UserAddress。但这与 LiveID 帐户无关。是关于office用户设置的。

如何获取所需信息?

我发现只有一种方法可以检索此信息 - 读取注册表... 有关键HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office.0\Common\Identity\Identities\ 如果是 Office 2016。有像 xxxxx_LiveId 这样的子项,其中 xxxxx 匹配 ProviderId 值。

您至少可以从该子项中读取 EmailAddress 个值。

所以我写了一些 C# 代码来检索登录 LiveID 用户的电子邮件地址:

string GetUserEmailFromOffice365()
{
    string Version = "16.0"; //TODO get from AddIn
    string identitySubKey = $@"Software\Microsoft\Office\{Version}\Common\Identity\Identities";

    using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(identitySubKey))
    {
        if (key != null && key.SubKeyCount > 0)
            {
                foreach (var subkeyName in key.GetSubKeyNames())
                {
                    using (var subkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey($@"{identitySubKey}\{subkeyName}"))
                    {
                        object value = null;
                        try
                        { 
                            value = subkey.GetValue("EmailAddress");
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex);
                        }
                        if (value != null && value is string)
                        {
                            return value as string;
                        }
                    }
                }
            }
    }
    return null;
}

当然你不应该硬编码 Version 值。您可以使用 ThisAddIn_Startup 方法从 ThisAddIn.cs 文件中的 Globals.ThisAddIn.Application.Version 获取并记住 office 版本。