none
Checks users Exists in user group or not? RRS feed

  • Question

  • Hi All,

    bool userExsists = SPContext.Current.Web.CurrentUser.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == "groupname".ToLower());

    Is there ay alternative for findings that user is in group or not? Is it best way to achieve this?

    Wednesday, October 15, 2014 9:38 AM

Answers

  • bool userExsists = SPContext.Current.Web.CurrentUser.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == "groupname".ToLower());
    Friday, October 17, 2014 3:13 AM

All replies

  • Hi,

    To check if a user exists in user group, please use the code below:

                string userName = "contoso\\admin";//your user account
                string groupName = "SP Members";// your user group
                using (SPSite spSite = new SPSite("http://sp")) // your site collection URL
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPUser user = spWeb.EnsureUser(userName);
                        if (user.Groups.Cast<SPGroup>().Any(g => g.Name.Equals(groupName)))
                        {
                            Console.WriteLine("User " + userName + " is a member of group " + groupName);
                        }
                        else
                        {
                            Console.WriteLine("User " + userName + " is NOT a member of group " + groupName);
                        }
                    }
                }
    

    Or you can use PowerShell command below:

    $w = get-spweb http://my
    $gs = $w.SiteGroups
    $g = $gs[12]
    $user = $g.Users.GetByEmail("user@domain.com")
    if($user -eq $null){write-host "User Not Found"}
    

    Best regards.

    Thanks

    Victoria Xia
    TechNet Community Support

    Thursday, October 16, 2014 3:31 AM
    Moderator
  • bool userExsists = SPContext.Current.Web.CurrentUser.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == "groupname".ToLower());
    Friday, October 17, 2014 3:13 AM