2012-06-12 83 views
2

我可以很好地添加用戶,但是無法將其添加到本地組。我得到這個錯誤: -將本地用戶添加到C#中的本地組中

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

這是我正在使用的代碼。我做錯了什麼?這只是本地機器,我絕對有權這樣做,並且該組明確存在。

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

回答

10

我寫了一些代碼很久以前的事,這需要不同的方法來你的,但據我可以告訴作品(只要沒有人報告的問題給我!)。對你有用嗎?

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

它的工作原理!非常感謝。 – nickthompson

+1

不錯。記住將它標記爲答案呢?我可以使用這些觀點,所以每個人都認爲我比實際上更知情。 P – PeteH

+0

救命恩,謝謝! +1 –

相關問題