Get the RootDSE in C#
Dec.03, 2009 in
.NET, Operating Systems, Programming, Windows
As you may already know, you can use the following to the domain name of the currently logged in user:
Environment.UserDomainName();
But what if you want the whole (fully qualified) domain name or root DSE? Well, that is a little trickier. You start by importing the usual namespaces:
using System.DirectoryServices; using System.DirectoryServices.ActiveDirectory;
And then you can use the following method to return an FQDN string (“mydomain”, or “mydomain.local”, or “subdomain.mydomain.local” for example, instead of “DC=mydomain” or “DC=mydomain,DC=local”):
public string GetRootDSE() { string sRootDSE = string.Empty; using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE")) { string sRootDSE_DN = rootDSE.Properties["defaultNamingContext"].Value.ToString(); if (sRootDSE_DN.Contains(",")) { string[] arrSubStrings = sRootDSE_DN.Split(','); foreach (string item in arrSubStrings) { string[] arrParts = item.Split('='); if (string.IsNullOrEmpty(sRootDSE)) { sRootDSE = arrParts[1]; } else { sRootDSE = string.Concat(sRootDSE, ".", arrParts[1]); } } } } return sRootDSE; }
So then the following would be true:
string myDomain = GetRootDSE(); // myDomain == "cyrusbuilt.net"
Good times

Leave a Reply
You must be logged in to post a comment.