将本地用户添加到C#中的本地组 [英] Adding a local user to a local group in C#

查看:119
本文介绍了将本地用户添加到C#中的本地组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以很好地添加用户,但是不能将其添加到本地组.我收到此错误:-

I can add a user perfectly well, but then I can't add it to a local group. I get this error:-

无法将成员添加到本地组或从本地组中删除,原因是 该成员不存在.

A member could not be added to or removed from the local group because the member does not exist.

这是我正在使用的代码.我做错了什么?这只是本地计算机,我绝对有权这样做,并且该组肯定存在.

Here is the code I'm using. What I am doing wrong? It's just the local machine, I definitely have rights to do it, and the group definifely exists.

        try
        {
            using (DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://" + serverName))
            {
                DirectoryEntries entries = hostMachineDirectory.Children;

                foreach (DirectoryEntry entry in entries)
                {
                    if (entry.Name.Equals(userName, StringComparison.CurrentCultureIgnoreCase))
                    {
                        // Update password
                        entry.Invoke("SetPassword", password);
                        entry.CommitChanges();
                        return true;
                    }
                }

                DirectoryEntry obUser = entries.Add(userName, "User");
                obUser.Properties["FullName"].Add("Used to allow users to login to Horizon. User created programmatically.");
                obUser.Invoke("SetPassword", password);
                obUser.Invoke("Put", new object[] {
                "UserFlags",
                0x10000
                });

                obUser.CommitChanges();

                foreach (string group in groups)
                {
                    DirectoryEntry grp = hostMachineDirectory.Children.Find(group, "group");
                    if (grp != null) { grp.Invoke("Add", new object[] { obUser.Path.ToString() }); }

                }
                return true;
            }
        }
        catch (Exception ex)
        {
            returnMessage = ex.InnerException.Message;
            return false;
        }

推荐答案

我很久以前就写了一些代码,它对您的代码采用了不同的方法,但据我所知,这是可行的(没有人向我报告问题!) .有什么用吗?

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();
        }
    }

这篇关于将本地用户添加到C#中的本地组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆