Friday, November 15, 2019

Checking if a User is in an SPGroup

Many know an example "How to check if user exists in a particular sharepoint group or not programatically":
using System;
using System.Linq;
using Microsoft.SharePoint;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "DOMAIN\\user";
            string groupName = "Home Members";
            using (SPSite Site = new SPSite("http://sp"))
            {
                using (SPWeb Web = Site.OpenWeb())
                {
                    SPUser user = Web.EnsureUser(userName);
                    if (user.Groups.Cast().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);
                    }
                }
            }
        }
    }
}
The example is excellent, in the end we will write "bool" using "ToUpper()", which at the machine level works much faster, because Microsoft optimized it:
bool checkuser = user.Groups.Cast().Any(g => g.Name.ToUpper() == "Home Members".ToUpper());
//or GetCurrentUser
bool checkgcuser = SPContext.Current.Web.CurrentUser.Groups.Cast().Any(g => g.Name.ToUpper() == "Home Members".ToUpper());
Happy Coding!

No comments:

Post a Comment