在C#中将本地用户添加到本地组

我可以很好地添加用户,但是我无法将其添加到本地组。 我收到这个错误: –

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

这是我正在使用的代码。 我做错了什么? 它只是本地机器,我绝对有权这样做,而且该组织确实存在。

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

我在很久以前写过一些代码,它们采用了与你不同的方法,但就我所说的而言(只要没有人向我报告过问题!)。 对你有用吗?

  ///  /// Adds the supplied user into the (local) group ///  /// the full username (including domain) /// the name of the group /// 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 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(); } }