c#使用LDAP操作AD域,这段代码主要实现AD域目录的查询。
先传入空的参数,查询出根目录信息,再根据名称和类型查询想要的信息。
1.定义查询返回实体类
public class QueryADTreeModelView
{
/// <summary>
/// 父级名称
/// </summary>
public string ParentName { get; set; }
public List<QueryADTreeModel> ADTreeModel { get; set; }
}
public class QueryADTreeModel
{
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 类型
/// </summary>
public string Type { get; set; }
/// <summary>
/// id
/// </summary>
public string Id { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
}
2.查询AD域树目录
#region 查询AD域目录
/// <summary>
/// 查询AD域树
/// </summary>
/// <returns></returns>
public async Task<JsonView> QueryADTree(QueryADTreeDto dto)
{
var result = new JsonView();
QueryADTreeModelView ADTreeModel = new QueryADTreeModelView();
try
{
DirectoryEntry entry = operateADHelper.IsConnected();//连接AD域
List<QueryADTreeModel> modelList = new List<QueryADTreeModel>();
if (!string.IsNullOrEmpty(dto.Name) && !string.IsNullOrEmpty(dto.Type))//名称类型不为空则查询
{
string NewDEPath = GetEntryPath(dto.Name, dto.Type);//获取路径
DirectoryEntry NewDE = entry.Children.Find(NewDEPath, dto.Type);//查找
entry = NewDE;
}
foreach (DirectoryEntry subEntry in entry.Children)
{
QueryADTreeModel model = new QueryADTreeModel();
model.Name = subEntry.Name.Replace("DC=", "").Replace("CN=", "").Replace("OU=", "");//名称
model.Id = subEntry.NativeGuid;//id
model.Type = subEntry.SchemaClassName;//类型名称
if (subEntry.Properties.Contains("description"))//描述属性存在
{
model.Description = subEntry.Properties["description"][0].ToString();
}
modelList.Add(model);
}
ADTreeModel.ADTreeModel = modelList;
ADTreeModel.ParentName = entry.Name.Replace("DC=", "").Replace("CN=", "").Replace("OU=", "");//主名称
result.Data = ADTreeModel;
result.Code = 0;
result.Msg = "查询成功";
return result;
}
catch (DirectoryServicesCOMException ex)
{
result.Code = 1;
result.Msg = "查询失败" + ex.Message.ToString();
return result;
}
}
#endregion
查询方法返回的是名称,类型,id和描述这样就实现了基本信息的展现;