How to Check if SPGroup Exists


The SharePoint API lacks methods to check for the security group existence. Here is utilities that do the job:

        public static bool GroupExists(SPGroupCollection groups, string name)

        {

            if (string.IsNullOrEmpty(name) ||

                (name.Length > 255) ||

                (groups == null) ||

                (groups.Count == 0))

                return false;

            else

                return (groups.GetCollection(new String[] { name }).Count > 0);

        }

 

        public static bool GroupExists(SPGroupCollection groups, int id)

        {

            if ((id < 0) ||

                (groups == null) ||

                (groups.Count == 0))

                return false;

            else

                return (groups.GetCollection(new Int32[] { id }).Count > 0);

        }


Comments (8)
  1. Andy Parkhill says:

    Just to make you aware that your code is being plagiarized here:

    aarohblah.blogspot.com/…/how-to-check-if-spgroup-exist.html

    Thanks for the original post.

  2. Michael says:

    Thanks for the code, pretty cool because checking if the group is null doesn't work.

  3. Khaniya says:

    On Execution of above code I face an error "Operation is not valid due to the current state of the object." why so?

    can anybody help on this?

  4. Scott says:

    I get the same error… anyone assist please?

  5. I get the same error – has anyone found a fix for the Operation is not valid due to the current state of the object." error

  6. Thanks for the help!  Much appreciated.

Comments are closed.

Skip to main content