Search code examples
c#ms-officevstooffice365windows-live-id

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


I develop VSTO add-in for Word, Excel etc. And I need to get information about user currently logged in Office application. I need at least an email address.

enter image description here

I found these properties Globals.ThisAddIn.Application.UserName, .UserInitials and .UserAddress. But it's not about LiveID account. It is about office user settings.

How can I get required information?


Solution

  • I found only one way to retrieve this information - read the Registry... There are key HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Common\Identity\Identities\ if it is Office 2016. There are subkey like xxxxx_LiveId where xxxxx matches to ProviderId value.

    You can read at least EmailAddress value from that subkey.

    So I wrote some C# code for retrieve an e-mail address of logged in LiveID user:

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

    Of cource you shouldn't hardcode Version value. You can get and remember office version from Globals.ThisAddIn.Application.Version in ThisAddIn.cs file in ThisAddIn_Startup method.