如何检测我的程序是否在 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");
来自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 的一种更简洁的方法。
我发现了一些有用的东西:
使用 System.Net.NetworkInformation;
IPGlobalProperties.GetIPGlobalProperties().DomainName;
与本地用户和域用户一起使用。