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

前端 未结 5 496
陌清茗
陌清茗 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: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).

提交回复
热议问题