Managed wrapper for unmanaged function NetUserGetLocalGroups

    class NetAPIHelper

    {

        /// <summary>

        /// NET_API_STATUS

        /// </summary>

        enum NET_API_STATUS : int

        {

            /// <summary>

            /// The call succeeds

            /// </summary>

            NERR_Success = 0,

            /// <summary>

            /// The user name could not be found.

            /// </summary>

            NERR_UserNotFound = 2221,

            /// <summary>

            /// This computer name is invalid.

            /// </summary>

            NERR_InvalidComputer = 2351,

            /// <summary>

/// More entries are available. Specify a large enough buffer to

/// receive all entries.

            /// </summary>

            ERROR_MORE_DATA = 2123,

            /// <summary>

            /// The user does not have access to the requested information.

            /// </summary>

            ERROR_ACCESS_DENIED = 5

        }

 

        /// <summary>

        /// Описание функции см. в MSDN, Network Management Functions, User

  /// Functions

        /// </summary>

        [DllImport("Netapi32.dll", ExactSpelling = true, CharSet =CharSet.Auto)]

        private extern static int NetUserGetLocalGroups([MarshalAs(UnmanagedType.LPWStr)] string servername,

                        [MarshalAs(UnmanagedType.LPWStr)] string username,

                        int level,

                        int flags,

                        out IntPtr bufptr,

                        int prefmaxlen,

                        out int entriesread,

                        out int totalentries);

 

        /// <summary>

  /// Описание функции см. в MSDN, Network Management Functions, API              /// Buffer Functions

        /// </summary>

        [DllImport("Netapi32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]

        private static extern int NetApiBufferFree(IntPtr Buffer);

 

        /// <summary>

        /// Описание см. в MSDN, Platform SDK: Network Management,

        /// LOCALGROUP_USERS_INFO_0

        /// </summary>

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]

        private struct LOCALGROUP_USERS_INFO_0 { public string groupname; }

 

        /// <summary>

        /// Получает имена групп, к которым принадлежит пользователь

        /// </summary>

        /// <param name="userName">имя пользователя</param>

        /// <returns>Имена групп пользователя</returns>

        public static string[] GetLocalUserGroups(string userName)

        {

            int entriesread;

            int totalentries;

            int offset = 0;

            StringCollection groupNames = new StringCollection();

 

            LOCALGROUP_USERS_INFO_0 group;

            IntPtr groupPointer = (IntPtr)0;

            try

            {

                NET_API_STATUS nStatus = (NET_API_STATUS)NetUserGetLocalGroups

(null, userName, 0, 0, out groupPointer, Int32.MaxValue, out entriesread, out totalentries);

 

                if (nStatus != NET_API_STATUS.NERR_Success)

                {

                    string errorMessage = "";

                    switch (nStatus)

                    {

                        case NET_API_STATUS.ERROR_ACCESS_DENIED:

                            errorMessage = "Недостаточно прав для получения информации о группе";

                            break;

                        case NET_API_STATUS.ERROR_MORE_DATA:

                            errorMessage = "Недостаточно выделено памяти для всех записей о группах";

                            break;

                        case NET_API_STATUS.NERR_InvalidComputer:

                            errorMessage = "Некорректное имя компьютера";

                            break;

                        case NET_API_STATUS.NERR_UserNotFound:

                            errorMessage = "Пользователь не найден";

                            break;

                    }

          throw new NetAPIHelperException("Ошибка при получении имени группы пользователей: " + errorMessage);

                }

                for (int i = 0; i < entriesread; i++)

                {

                    IntPtr pointer = new IntPtr(groupPointer.ToInt32() + offset);

group = (LOCALGROUP_USERS_INFO_0)Marshal.PtrToStructure(pointer, typeof(LOCALGROUP_USERS_INFO_0));

                    offset += Marshal.SizeOf(typeof(LOCALGROUP_USERS_INFO_0));

                    groupNames.Add(group.groupname);

                }

            }

            catch (NetAPIHelperException e)

            {

                throw e;

            }

            finally

            {

                //Освобождаем память, выделенную для структуры. !Память

    // выделяется внутри функции

                //NetUserGetLocalGroups

                NetApiBufferFree(groupPointer);

            }

            string[] result = new string[groupNames.Count];

            groupNames.CopyTo(result, 0);

            return result;

        }

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s