Adding a local user to a local group in C#

烈酒焚心 提交于 2019-12-03 21:18:06

I wrote some code ages ago which takes a different approach to yours, but as far as I can tell works (insofar as nobody ever reported problems to me!). Any use to you?

    /// <summary>
    /// Adds the supplied user into the (local) group
    /// </summary>
    /// <param name="userName">the full username (including domain)</param>
    /// <param name="groupName">the name of the group</param>
    /// <returns>true on success; 
    /// false if the group does not exist, or if the user is already in the group, or if the user cannont be added to the group</returns>
    public static bool AddUserToLocalGroup(string userName, string groupName)
    {
        DirectoryEntry userGroup = null;

        try
        {
            string groupPath = String.Format(CultureInfo.CurrentUICulture, "WinNT://{0}/{1},group", Environment.MachineName, groupName);
            userGroup = new DirectoryEntry(groupPath);

            if ((null == userGroup) || (true == String.IsNullOrEmpty(userGroup.SchemaClassName)) || (0 != String.Compare(userGroup.SchemaClassName, "group", true, CultureInfo.CurrentUICulture)))
                return false;

            String userPath = String.Format(CultureInfo.CurrentUICulture, "WinNT://{0},user", userName);
            userGroup.Invoke("Add", new object[] { userPath });
            userGroup.CommitChanges();

            return true;
        }
        catch (Exception)
        {
            return false;
        }
        finally
        {
            if (null != userGroup) userGroup.Dispose();
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!