简体   繁体   中英

Unable to get user by email from Sharepoint

I am trying to access the user by his email id. But I am getting user not found exception, even when I am able to login to office 365 portal using that email id. Here is the code snippet:

//Creating Context
Uri webFullUrl = new Uri(URL);
string username = UserName;
string password = Password;
SecureString secureString = new SecureString();
for (int i = 0; i < password.Length; i++)
{
  char c = password[i];
  secureString.AppendChar(c);
}
SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(username, secureString);
ClientContext clientContext = new ClientContext(webFullUrl)
        {
          Credentials = credentials
        };
User user = clientContext.Web.SiteUsers.GetByEmail(email);
clientContext.ExecuteQuery();

When I execute the last line, I get an exception User not found . Anyone has any idea about how to get user from email? I have user's email id only.

I found the solution, its a two step process, though its working I am not sure if this is correct way. My code looks like:

public User GetUserByEmail(ClientContext clientContext, string email)
{
 try
   {
     ClientResult<Microsoft.SharePoint.Client.Utilities.PrincipalInfo> persons =
     Microsoft.SharePoint.Client.Utilities.Utility.ResolvePrincipal(clientContext,                         clientContext.Web, email,
     Microsoft.SharePoint.Client.Utilities.PrincipalType.User,Microsoft.SharePoint.Client.Utilities.PrincipalSource.All, null, true);
     clientContext.ExecuteQuery();
     Microsoft.SharePoint.Client.Utilities.PrincipalInfo person = persons.Value;
     User user = clientContext.Web.SiteUsers.GetByLoginName(person.LoginName);
     clientContext.ExecuteQuery();
     return user;
   }
   catch
   {
     return null;
   }

}

I took the help from snippet given Here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM