Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to check if a local group already exists

Is there a way to find out if a local group already exists? My "best" solution works by catching an exception. Is there a way to do achieve the same goal without catching an exception?

var machine = Environment.MachineName;
var server = new DirectoryEntry(string.Format("WinNT://{0},Computer", machine));
bool groupExists = true;
try
{
   server.Children.Find("MyGroup", "group");
}
catch (COMException ex)
{
   if (ex.ErrorCode == -2147022676)
      groupExists = false;
   else
      throw;
}
like image 404
gsharp Avatar asked Jan 12 '23 11:01

gsharp


2 Answers

You can try the below code

        var machine = Environment.MachineName;
        var server = new DirectoryEntry(string.Format("WinNT://{0},Computer", machine));
        bool exists = server.Children.Cast<DirectoryEntry>().Any(d => d.SchemaClassName.Equals("Group") && d.Name.Equals("Administrators"));
like image 196
cli Avatar answered Jan 27 '23 20:01

cli


Alternatively you could use the PrincipalContext class as follows:

using(var local = new PrincipalContext(ContextType.Machine)) 
{
    var group = GroupPrincipal.FindByIdentity(local, "MyGroup");
    var groupExists = group != null; 
}
like image 24
Hastarin Avatar answered Jan 27 '23 19:01

Hastarin