CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Monday, September 25, 2006

Getting a computer's details from Active Directory in .NET

Description: Example shows how to get details of a computer in a domain from Active Directory. This example returns a string array of details. But it could be easily modified to do something else.

        /// <summary>
        /// Get computer details from active directory.  Return in a string array.
        /// </summary>
        /// <param name="Domain">string.  Domain name. 
        ///        Leave blank to use the default domain.</param>
        /// <param name="UserName">string.  Host name.</param>
        /// <returns>string[].  Array of the computers properties from Active Directory.</returns>
        public static string[] GetComputerDetails(string Domain, string HostName)
        {
            try
            {
                // if the domain is left blank, lets use the default domain
                if (Domain.Length == 0)
                    Domain = (string)new DirectoryEntry("LDAP://RootDSE").
                                          Properties["defaultNamingContext"][0];
                
                DirectoryEntry Entry = new DirectoryEntry("LDAP://" + Domain);
                DirectorySearcher Search = new DirectorySearcher(Entry);
                Search.Filter = string.Format("(&(objectCategory=computer)(cn={0}))", HostName);
                SearchResult Result = Search.FindOne();
                if (Result == null)
                    return null;
                else
                {
                    ArrayList Results = new ArrayList();
                    foreach (string Key in ((Hashtable)Result.Properties.PropertyNames.SyncRoot).Keys )
                    {
                        for (int i = 0; i < Result.Properties[Key].Count; i++)
                            Results.Add(Key + "[" + i + "]: " + Result.Properties[Key][i].ToString());
                    }
                    return (string[])Results.ToArray(typeof(string));
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

Post a Comment