19

Am I missing something here? There should be a method to check if a user exist, which doesn't throw an error if it doesn't. EnsureUser() is not applicable, because that method creates a new user if it doesn't exist.

At the time, this is what I do, but I think it should be easier in some way.

var userName = @"DOMAIN\UserName"
var userString = string.Empty;
try
{
  SPUser user = web.AllUsers[userName];
  userString = user.ID + ";#" + user.LoginName;
} 
catch (Exception e)
{
  //The user does not exist, but it's okay
  Console.WriteLine("The user does not exist, but it's okay: " +e.InnerException);
}
2
  • I would probably just use the AllUsers collection too.
    – Kit Menke
    Mar 16, 2011 at 13:53
  • 7 years later.... I don't see why we wouldn't just use EnsureUser. No harm in ensuring the user for the site collection as far as I can tell.
    – tarjeieo
    Jun 29, 2018 at 9:51

4 Answers 4

7

Personally, I'd use this:

  var user = web.AllUsers.Cast<SPUser>().FirstOrDefault(u => u.LoginName == userName);
  if (user != null) 
  {
    ...
  }
1
  • 1
    This is big performance gap
    – IAfanasov
    Apr 25, 2012 at 6:23
5

You should use:

using (SPSite site = new SPSite(_upa))
{

    SPServiceContext context = SPServiceContext.GetContext(site);
    UserProfileManager _upaManager = new UserProfileManager(context);

    // Chek if user exists
    if( _upaManager.UserExists("mydomain\\myuser")}
    {
        // The user exists
    }
    else{
        // The User doesn't exists
    }
}
1
  • At UserProfileManager declaration it throws error if user profile doesn't exists: "An exception of type 'Microsoft.Office.Server.UserProfiles.UserProfileApplicationNotAvailableException' occurred in Microsoft.Office.Server.UserProfiles.dll but was not handled in user code Additional information: UserProfileApplicationNotAvailableException_Logging :: UserProfileApplicationProxy.GetRawPartitionID has null proxy" Apr 13, 2016 at 11:49
3

If you have an email address you could use GetByEmail then check for null - cleaner than throwing Exceptions I reckon.

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spusercollection.getbyemail.aspx

4
  • Yep, James is correct that you can get it by email or id, and you have to do all that exception handling if you want to get user by login. Maybe it would been better if AllUsers["username"] could return null if it doesnt find such user, but it can be job for a extension method. Mar 16, 2011 at 8:30
  • I don't want to query for e-mail, since most people have several, and it's not certain which e-mail is associated with the user profile.
    – tarjeieo
    Mar 16, 2011 at 8:52
  • 3
    In SP2007, GetByEmail will throw SPException if the email address is not found.
    – Bill Yang
    Aug 3, 2011 at 20:57
  • 2
    @Bill: Just had a look, it seems to do that in 2010 as well... that's a pretty bad implementation to be honest.
    – James Love
    Aug 3, 2011 at 21:07
2

I offer another practice - query UsesInfoList:

                            using (var site = p)
                            {
                                using (var root = site.RootWeb)
                                {
                                    var query = new SPQuery();
                                    query.ExpandRecurrence=false;
                                    query.ExpandUserField = false;
                                    query.Query =string.Format(
                                        @"<Where><Eq><FieldRef Name=""Name"" /><Value Type=""Text"">{0}</Value></Eq></Where>", 
                                        newLogin);
                                    var items = root.SiteUserInfoList.GetItems(query);
                                    if (items == null || items.Count == 0)
                                    {
                                        continue;
                                    }
                                    var userID = items.OfType<SPListItem>().First().ID;
                                    var user = root.SiteUsers.GetByID(userID);
                                    if (!user.LoginName.Equals(newLogin))
                                    {
                                        throw new InvalidOperationException("Unable to get user id by CAML " + query.Query);
                                    }
                                    user.Name = fullName;
                                    user.Email = newEmail;
                                    user.Update();
                                }
                            }
                        }
                        catch (Exception err)
                        {
                            Log.Error(err);
                            buf.AppendLine(err.ToString());
                        }
1
  • var userID = items[0].ID;
    – IAfanasov
    Apr 25, 2012 at 6:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.