Get domain name

Osvier picture Osvier · Nov 12, 2010 · Viewed 99.8k times · Source

My computer is in a Domain (Active Directory) and I need to get the domain name dynamically. I found the following code on the internet:

SelectQuery query = new SelectQuery("Win32_ComputerSystem");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
    foreach (ManagementObject mo in searcher.Get())
    {
        if ((bool)mo["partofdomain"])
        {
            this.Domain = mo["domain"].ToString();
            break;
        }
    }
 }

It works exactly as I want and returns exactly the domain name as I want (when I am logged as Administrator). If the user is not a Domain Admin, I have an Access denied exception.

Does anybody know how to get the domain even with non-domain administrator users?

NOTE: I have found this solution on Internet System.Environment.UserDomainName; but it only gives me a part of the domain name.

I.e. my domain is: something.domain.com and the UserDomainName returns only something.

Answer

Pieter van Ginkel picture Pieter van Ginkel · Nov 12, 2010

Why are you using WMI? Can't you use the standard .NET functionality?

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;