2010-07-01 5 views
10

Sto cercando un modo per creare un gruppo di utenti locale al livello di programmazione. Ho trovato molti esempi su come interrogare e aggiungere utenti, ma non riesco a capire nulla su come creare un nuovo gruppo.Come creare un gruppo di utenti locale (in C#)

var dirEntry = new DirectoryEntry(
         "WinNT://" + Environment.MachineName + ",computer"); 

/* Code to test if the group already exists */    

if (!found) 
{ 
    DirectoryEntry grp = dirEntry.Children.Add(groupName, "Group"); 
    dirEntry.CommitChanges(); 
} 

Questo è quello che ho arrivato a, ma so che è sbagliato, come CommitChanges() getta solo un NotImplementedException.

ho usato questo come un campione, ma non riesco nemmeno a farlo funzionare (grazie MS):

http://msdn.microsoft.com/en-us/library/ms815734

Chiunque ha un frammento di codice che posso usare per creare un nuovo locale gruppo?

risposta

10

questo funziona per me:

var ad = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); 
DirectoryEntry newGroup = ad.Children.Add("TestGroup1", "group"); 
newGroup.Invoke("Put", new object[] { "Description", "Test Group from .NET" }); 
newGroup.CommitChanges(); 

adattato da this articolo sugli utenti.

Sembra che tu abbia perso l'Invoke "Put" nel tuo esempio: immagino sia per questo che stai vedendo NotImplementedException.

+0

Sì, è esattamente quello che è successo. Ho trovato un esempio sull'aggiunta di un utente e su quella chiamata "Aggiungi". Lo stesso codice con "Put" funziona ora. Grazie! –

+0

Non ho abbastanza punti per votare, ma ho accettato la tua risposta. Grazie ancora. –

+0

@ the-diamond-z - grazie! Mi sono reso conto che non ho votato in anticipo la tua domanda, quindi ho appena fatto. Benvenuto in Stack Overflow! –

6

Si può provare quanto segue (non ho provato io stesso):

PrincipalContext context = new PrincipalContext(ContextType.Machine); 
GroupPrincipal group = new GroupPrincipal(context); 
group.Name = model.Name; 
group.Save(); 

Questo utilizza System.DirectoryServices.AccountManagement.

+4

Perché dovresti pubblicare una risposta senza nemmeno provarla? È solo rumore di linea che porta a inseguimenti di oche selvagge. –

+2

Per essere onesti, funziona ... – Doogal

+0

Puoi anche passare il nome del gruppo nel costruttore come in: GroupPrincipal group = new GroupPrincipal (context, "MyLocalGroup") –