无法通过电子邮件从 SharePoint 获取用户

本文关键字:SharePoint 获取 用户 电子邮件 | 更新日期: 2023-09-27 18:35:21

我正在尝试通过用户的电子邮件ID访问用户。但是我遇到用户未找到异常,即使我能够使用该电子邮件 ID 登录到 Office 365 门户。以下是代码片段:

//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();

当我执行最后一行时,我得到一个异常User not found.有人知道如何从电子邮件中获取用户吗?我只有用户的电子邮件 ID。

无法通过电子邮件从 SharePoint 获取用户

我找到了解决方案,这是一个两步过程,尽管它的工作我不确定这是否正确。我的代码如下所示:

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

我从这里给出的片段中得到了帮助。