2017-04-27 10 views
0

Vous essayez d'ajouter un nom d'hôte à un groupe de domaines et j'obtiens l'exception There is a naming violation.C# Ajout d'un PC au groupe de domaines AD

J'ai vu plusieurs réponses acceptées couvrant cette chose exacte et pour autant que je sache que ma syntaxe est correcte.

try 
{ 
    DirectoryEntry de = new DirectoryEntry("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Groups,OU=US,DC=aa,DC=bbbbb,DC=com"); 
    string hostname = "CN=" + SystemInformation.ComputerName; 
    DirectoryEntry add = de.Children.Add(hostname, "Computer"); 
    add.CommitChanges(); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString()); 
} 

Toute aide serait grandement appréciée.

Répondre

0

J'ai trouvé quel était le problème - je devais passer le nom distinctif, plutôt que juste le nom d'hôte ... qui aurait dû être évident, si j'avais effectivement lu le document MSDN ... Aussi, de.Children.Add() peut être une méthode valide pour accomplir ceci (c'était une réponse acceptée sur SE, pour .Net 3.5 IIRC), mais j'ai utilisé de.Properties["member"].Add() pour l'accomplir.

code source pour toutes les Googlers Mise à jour là-bas:

private void DoStuff(object sender, EventArgs e) 
{ 
    using (Process addgroup = new Process()) 
    { 
     string hostname = Environment.MachineName; 
     AddMemberToGroup("LDAP://aa.bbbbb.com/CN=Group,OU=Application,OU=Group,OU=US,DC=aa,DC=bbbbb,DC=com", hostname); 
    } 
} 

private void AddMemberToGroup(string ldapString, string host) 
{ 
    try 
    { 
     DirectoryEntry de = new DirectoryEntry(ldapString); 
     string distHost = GetDistinguishedName(host); 
     if (!String.IsNullOrEmpty(distHost)) 
     { 
      de.Properties["member"].Add(distHost); 
      de.CommitChanges(); 
     } 
     else 
     { 
      MessageBox.Show("Distinguished Host Name returned NULL"); 
     } 
    } 
    catch(Exception ex) 
    { 
     MessageBox.Show("Group join failed" + Environment.NewLine + Environment.NewLine + ex.ToString()); 
    } 
} 

private string GetDistinguishedName(string compName) 
{ 
    try 
    { 
     PrincipalContext pContext = new PrincipalContext(ContextType.Domain); 
     ComputerPrincipal compPrincipal = ComputerPrincipal.FindByIdentity(pContext, compName); 
     return compPrincipal.DistinguishedName; 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show("Failed to get the Distinguished Hostname from Active Directory" + Environment.NewLine + Environment.NewLine + ex.ToString()); 
     return null; 
    } 
}