Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

c# - Get domain name

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...