How do I detect if my program runs in an Active Directory environment?

前端 未结 5 482
陌清茗
陌清茗 2020-12-31 16:51

How do I detect if my program runs in an Active Directory environment?

I\'m using C# and .Net 2.0

相关标签:
5条回答
  • 2020-12-31 17:03

    This code will check if the Computer itself is a member of a domain

    using System.DirectoryServices.ActiveDirectory;
    
    
    bool isDomain = false;
    
    try
    {
        Domain.GetComputerDomain();
        isDomain = true;
    }
    catch (ActiveDirectoryObjectNotFoundException)
    {
    }
    

    However the computer can be in a domain, but the currently logged in user may be a local user account. If you want to check for this use the Domain.GetCurrentDomain() function

    0 讨论(0)
  • 2020-12-31 17:03

    One way might be to query the LOGONSERVER environmental variable. That'll give the server name of your AD controller... Which, as far as I know, will be blank (or match current workstation? Not sure) if it isn't currently logged into a domain.

    Example Usage:

    string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER"); 
    
    0 讨论(0)
  • 2020-12-31 17:08

    Try getting Environment.UserDomainName and comparing it to Environment.MachineName. If the two are the same then it's likely that the user does not have a domain. If they are not the same then the user is logged into a domain which must have a directory server.

    0 讨论(0)
  • 2020-12-31 17:22

    I found something that works:

    using System.Net.NetworkInformation;

    IPGlobalProperties.GetIPGlobalProperties().DomainName;

    Works with a local user and a domain user.

    0 讨论(0)
  • 2020-12-31 17:25

    From http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.path.aspx

    To bind to the current domain using LDAP, use the path "LDAP://RootDSE", then get the default naming context and rebind the entry.

    So without a domain the binding to "LDAP://RootDSE" should either fail or return nothing. I didn't try it for myself.

    use System.DirectoryServices; // add reference to system.directoryservices.dll
    
    ...
    
    DirectoryEntry ent = new DirectoryEntry("LDAP://RootDSE");
    String str = ent.Properties["defaultNamingContext"][0];
    DirectoryEntry domain = new DirectoryEntry("LDAP://" + str);
    

    This is definitely a cleaner way of checking for an Active Directory than relying on an environment variable (which the user could delete or add to spoof the program).

    0 讨论(0)
提交回复
热议问题