有没有办法找出本地组是否已经存在?我的“最佳”解决方案通过捕获异常来工作。有没有办法在没有捕获异常的情况下实现相同的目标?
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;
}
答案 0 :(得分:7)
您可以尝试以下代码
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"));
答案 1 :(得分:0)
或者您可以使用PrincipalContext类,如下所示:
using(var local = new PrincipalContext(ContextType.Machine))
{
var group = GroupPrincipal.FindByIdentity(local, "MyGroup");
var groupExists = group != null;
}