绑定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();
        }

 

 
Posted on 2014-06-05 16:18  dotnba  阅读(618)  评论(0编辑  收藏  举报