Okay so its pretty easy to get the fully qualified domain name (FQDN).
using System.DirectoryServices; using System.DirectoryServices.ActiveDirectory; Console.WriteLine(Domain.GetCurrentDomain().Name)
But what happens if you want to get the old-skool netbios name. The quickest way is to use System.Environment:
using System Console.WriteLine(System.Environment.UserDomainName)
This gets the network domain name associated with the current user. So not much good if your code is running as a service that could well be configured to run at Network Account. Surely you can do this using DirectoryServices? Bit of Googling and coding and we have a nice little extension method which does just that
/// <summary> /// Defines extentions made to the <see cref="Domain"/> class. /// </summary> public static class DomainExtensions { public static string GetNetbiosName(this Domain domain) { // Bind to RootDSE and grab the configuration naming context DirectoryEntry rootDSE = new DirectoryEntry(@"LDAP://RootDSE"); DirectoryEntry partitions = new DirectoryEntry(@"LDAP://cn=Partitions," + rootDSE.Properties["configurationNamingContext"].Value); DirectoryEntry domainEntry = domain.GetDirectoryEntry(); //Iterate through the cross references collection in the Partitions container DirectorySearcher directorySearcher = new DirectorySearcher(partitions) { Filter = "(&(objectCategory=crossRef)(ncName=" + domainEntry.Path .Replace("LDAP://", string.Empty) .Replace(domain.Name + "/", string.Empty) + "))", SearchScope = SearchScope.Subtree }; directorySearcher.PropertiesToLoad.Add("nETBIOSName"); //Display result (should only be one) SearchResultCollection results = directorySearcher.FindAll(); if (results.Count == 0) { return null; } return results[0].Properties["nETBIOSName"][0].ToString(); } }
Usage:
Domain.GetCurrentDomain().GetNetbiosName()
Note You can also retrieve the netbios entry using netapi32.dll http://blog.dotsmart.net/2009/03/11/getting-a-machine%E2%80%99s-netbios-domain-name-in-csharp