我遇到一个问题,我有一个列表ID-我必须在listID中找到具有ID的spuser或spgroup的ID列表

我尝试了以下操作,但它引发了例外

              foreach (var id in ID)
                {
                    SPUser spUser = web.SiteUsers.GetByID(Convert.ToInt32(id));
                    if (spUser != null)
                    {
                        lstUsers.Add(spUser.LoginName);
                         continue;
                    }
                    SPGroup spGroup = web.SiteGroups.GetByID(Convert.ToInt32(id ));
                    if (spGroup != null)
                    {
                        lstGroups.Add(spGroup.LoginName);
                         continue;

                    }

                }

请建议该怎么办!!!

有帮助吗?

解决方案

我建议两个更改。

  1. 利用 SPFieldUserValue. 。如果用户不存在,则不会引发异常。
  2. 使用 SPGroupCollection.GetCollection(int[] ids)

    SPUserCollection users = web.SiteUsers;
    SPGroupCollection groups = web.SiteGroups;
    foreach (var id in ID)
    {
      // try to get user-name
      SPUser spUser = new SPFieldUserValue(web, Convert.ToInt32(id), null).User;
      if (spUser != null)
      {
        lstUsers.Add(spUser.LoginName);
        continue;
      }
      // try to get group-name
      var foundGroups = groups.GetCollection(new int[] { Convert.ToInt32(id) });
      if (foundGroups.Count > 0) 
      {
        lstGroups.Add(foundGroups[0]);
        continue;
      }
      // If execution reaches this point: Nothing found with this id
    }
    

其他提示

如果我正确地阅读了您的问题:您的列表呼叫 ID 其中您具有数字ID(用户和组ID),并希望将与ID相对应的用户或组的名称添加到另一个列表(称为LSTUSER或LSTGROUPS)。

如果处理ID是组的ID,则可以预期的例外。功能 web.SiteUsers.GetById() 当找不到给定的ID时,引发异常,这是您首先尝试的。尝试将其包裹在 try-catch-堵塞。

奖金: 将站点用户和站点组存储在变量中,以避免在循环的每次迭代中从数据库中反复一次又一次地获取此信息。

SPUserCollection users = web.SiteUsers;
SPGroupCollection groups = web.SiteGroups;
foreach (var id in ID)
{
  // try to get user-name
  try{
    SPUser spUser = users.GetByID(Convert.ToInt32(id));
    if (spUser != null)
    {
      lstUsers.Add(spUser.LoginName);
      continue;
    }
  }catch(Exception){
     //  no user found with id.
  }

  // try to get group-name
  try {
    SPGroup spGroup = groups.GetByID(Convert.ToInt32(id ));
    if (spGroup != null)
    {
      lstGroups.Add(spGroup.LoginName);
      continue;
    }
  }catch(Exception){
     // no group found with id
  }

  // If execution reaches this point: Nothing found with this id
}
许可以下: CC-BY-SA归因
scroll top