如何检测我的程序是否在Active Directory环境中运行?

如何检测我的程序是否在Active Directory环境中运行?

我正在使用C#和.Net 2.0

尝试获取Environment.UserDomainName并将其与Environment.MachineName进行比较。 如果两者相同,那么用户可能没有域。 如果它们不相同,则用户登录到必须具有目录服务器的域。

此代码将检查计算机本身是否是域的成员

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

但是,计算机可以位于域中,但当前登录的用户可以是本地用户帐户。 如果要检查这个,请使用Domain.GetCurrentDomain()函数

一种方法可能是查询LOGONSERVER环境变量。 这将给出你的AD控制器的服务器名称…如果它当前没有登录到域,据我所知,这将是空白的(或匹配当前工作站?不确定)。

用法示例:

 string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER"); 

我找到了有用的东西:

使用System.Net.NetworkInformation;

IPGlobalProperties.GetIPGlobalProperties()域名。

适用于本地用户和域用户。

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

要使用LDAP绑定到当前域,请使用路径“LDAP:// RootDSE”,然后获取默认命名上下文并重新绑定该条目。

因此,如果没有域,对“LDAP:// RootDSE”的绑定应该失败或者不返回任何内容。 我没有为自己尝试。

 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); 

这绝对是一种检查Active Directory的方法,而不是依赖于环境变量(用户可以删除或添加以欺骗程序)。