0

How to check in C# if the current user is in a group or not? Thanks for help.

 using (SPSite SPsite = new SPSite("http://sp/sites/test"))
            {
                using (SPWeb web = SPsite.OpenWeb())
                {
                    SPUser user = web.CurrentUser;
                    SPGroupCollection groups = user.Groups;

                    foreach (SPGroup group in groups)
                    {
                        string groupName = group.Name;
                    }
                }
            }

CSOM not need.

6

1 Answer 1

2

If you want to achieve this using SSOM, I will recommend you trying the solutions given in below links:

  1. How to check if user exists in a particular SharePoint group or not programatically
  2. Checking if a SPUser is in an SPGroup

Code for reference:

using System;
using System.Linq;
using Microsoft.SharePoint;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "PERSEUS\\dmitry.kaloshin";
            string groupName = "Home Members";
            using (SPSite spSite = new SPSite("http://perseus"))
            {
                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);
                    }
                }
            }
        }
    }
}

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.