4

有没有办法找出本地组是否已经存在?我的“最佳”解决方案通过捕获异常来工作。有没有办法在不捕获异常的情况下实现相同的目标?

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

2 回答 2

8

你可以试试下面的代码

        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"));
于 2013-09-04T06:08:51.040 回答
1

或者,您可以使用PrincipalContext类,如下所示:

using(var local = new PrincipalContext(ContextType.Machine)) 
{
    var group = GroupPrincipal.FindByIdentity(local, "MyGroup");
    var groupExists = group != null; 
}
于 2015-03-10T04:36:59.997 回答