通过Guid获取DirectoryEntry对象

时间:2022-04-07 01:12:12
绑定DirectoryEntry对象通常有两种方法,一种是通过字符串(如通过ADsPath),一种是通过Guid(参见:http://msdn.microsoft.com/zh-cn/library/ms180842%28v=vs.80%29.aspx)。但是,通过Guid绑定时,需要指定目录服务器地址(除非绑定本地目录服务器),对于不指定目录服务器的情形就不适用。这个时候,可以通过objectGuid查找的方式获取DirectoryEntry对象。

        /// <summary>
/// 通过GUID获取目录对象
/// </summary>
/// <param name="deRoot"></param>
/// <param name="objectGUID"></param>
/// <returns></returns>
/// <example>GetDirectoryObjectByGUID(DirectoryEntry.Guid);</example>
public DirectoryEntry GetDirectoryObjectByGUID(DirectoryEntry deRoot,Guid objectGUID)
{
string queryGuid = Guid2OctetString(objectGUID);
DirectorySearcher searcher = new DirectorySearcher(deRoot, "(objectGUID=" + queryGuid + ")");
SearchResult sr = searcher.FindOne();
if (sr == null) return null;
return sr.GetDirectoryEntry();
}
 
        /// <summary>
/// 将GUID转换为16进制字符串
/// </summary>
/// <param name="objectGuid">Guid</param>
/// <returns></returns>
public static string Guid2OctetString(Guid objectGuid)
{
byte[] byteGuid = objectGuid.ToByteArray();
StringBuilder sb = new StringBuilder();
foreach (byte b in byteGuid)
{
sb.Append(@"\" + b.ToString("x2"));
}
return sb.ToString();
}