Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...