Machine's domain name in .NET?

江枫思渺然 提交于 2019-12-20 11:08:39

问题


There gotta be an easy way to do this, I can't believe there's none. I have scanned through net and found, like, 20 different methods to find in which domain current user is, but none to get domain (or workgroup) of current machine.

In unmanaged c++ this is retrieved by:

WKSTA_INFO_100 *buf;
NetWkstaGetInfo(NULL, 100, (LPBYTE*)buf);
domain_name = pBuf->wki100_langroup;

can someone help me, if there's a way to get same info in managed C# natively?

EDIT1: Folks, please read the question. I am NOT looking for user domain name.


回答1:


To get the current domain of the system on which your progam is running you can use System.DirectoryServices.ActiveDirectory.Domain.

Domain domain = Domain.GetComputerDomain();
Console.WriteLine( domain.Name );



回答2:


I work on a project where users could be anywhere; non-domain users on a domain machine, users on a non-domain machine, not directly connected to the domain on a third party network, etc. so depending on AD is already a non-starter.

System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName is far more reliable under all of these conditions.

http://blogs.msdn.com/b/trobbins/archive/2006/01/04/509347.aspx

https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipglobalproperties.domainname(v=vs.110).aspx?cs-save-lang=1&cs-lang=cpp#code-snippet-2

Imports System.DirectoryServices
Imports System.Net.NetworkInformation

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            MsgBox("Domain: " & ActiveDirectory.Domain.GetComputerDomain.Name)
        Catch ex As Exception
            MsgBox(ex.GetType.ToString & ": " & ex.Message)
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Try
            MsgBox("Domain: " & IPGlobalProperties.GetIPGlobalProperties().DomainName)
        Catch ex As Exception
            MsgBox(ex.GetType.ToString & ": " & ex.Message)
        End Try
    End Sub

End Class



回答3:


Using GetCurrentDomain is the same as Environment.UserDomainName, which works incorrectly if your program is running on a domain computer as a non-domain user. I've used the following code:

try
{
    return System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
}
catch (Exception)
{
    return Environment.UserDomainName;
}



回答4:


System.Environment.UserDomainName




回答5:


If you don't want to add a dependency to System.DirectoryServices, you can also call the NetGetJoinInformation API directly.



来源:https://stackoverflow.com/questions/508911/machines-domain-name-in-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!