【发布时间】:2008-09-26 16:35:07
【问题描述】:
如何检测我的程序是否在 Active Directory 环境中运行?
我正在使用 C# 和 .Net 2.0
【问题讨论】:
标签: c# active-directory
如何检测我的程序是否在 Active Directory 环境中运行?
我正在使用 C# 和 .Net 2.0
【问题讨论】:
标签: c# active-directory
尝试获取 Environment.UserDomainName 并将其与 Environment.MachineName 进行比较。如果两者相同,则用户可能没有域。如果它们不相同,则用户登录到必须具有目录服务器的域。
【讨论】:
此代码将检查计算机本身是否是域的成员
using System.DirectoryServices.ActiveDirectory;
bool isDomain = false;
try
{
Domain.GetComputerDomain();
isDomain = true;
}
catch (ActiveDirectoryObjectNotFoundException)
{
}
但是计算机可以在域中,但当前登录的用户可能是本地用户帐户。如果您想对此进行检查,请使用 Domain.GetCurrentDomain() 函数
【讨论】:
ActiveDirectoryObjectNotFoundException 也会被抛出。
一种方法可能是查询 LOGONSERVER 环境变量。这将给出您的 AD 控制器的服务器名称...据我所知,如果它当前未登录到域,它将为空白(或与当前工作站匹配?不确定)。
示例用法:
string ADServer = Environment.GetEnvironmentVariable("LOGONSERVER");
【讨论】:
我发现了一些有用的东西:
使用 System.Net.NetworkInformation;
IPGlobalProperties.GetIPGlobalProperties().DomainName;
适用于本地用户和域用户。
【讨论】:
来自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 的一种更简洁的方法。
【讨论】:
Domain.GetComputerDomain()或IPGlobalProperties.GetIPGlobalProperties().DomainName,如果成功了,就这样做。