Вопрос

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.

Это было полезно?

Решение

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);
                    }
                }
            }
        }
    }
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top