[英]How do I determine if “DirectoryEntry” found my user?
我正在使用这种在当前域中查找用户的简单方法,该方法适用于所有“存在”的用户,但我找不到任何方法来确定用户是否不存在。
string userLDAP = @"MYDOMAIN/username";
string path = "WinNT://" + userLDAP ;
DirectoryEntry root = new DirectoryEntry(path, null, null, AuthenticationTypes.Secure);
除了抛出异常之外,如何使用目录条目来确定用户是否不存在?
if (root.Properties != null)
if (root.Properties["objectSid"] != null) //// EXCEPTION HERE
if (root.Properties["objectSid"][0] != null)
为此目的最好使用DirectorySearcher ......
string userName = "TargetUserName";
using (DirectorySearcher searcher = new DirectorySearcher("GC://yourdomain.com"))
{
searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", userName);
using (SearchResultCollection results = searcher.FindAll())
{
if (results.Count > 0)
Debug.WriteLine("Found User");
}
}
此示例将搜索整个林,包括子域。 如果您只想定位单个域,请使用“LDAP://mydomain.com”而不是“GC://mydomain.com”。 您还可以使用DirectoryEntry提供searcher.SearchRoot作为搜索的根(即特定的OU或域)。
不要忘记大多数AD的东西是IDisposable所以如上所示妥善处理。
我认为检查DirectoryEntry对象是否指向现有AD条目的简单方法是使用静态Exists方法。
所以你的代码可能如下所示:
using(DirectoryEntry de = new DirectoryEntry(....)) {
// now we check if the related object exists
bool exists = DirectoryEntry.Exists(de.Path);
if(exists) {
// yes the objects exists
// do something
} // end if
} // end using
当然你可以省略exists变量。 我用它只是为了使声明更清晰。
您在寻找特定用户或所有用户吗?
我有一个应用程序通过检查帐户名来检查用户是否存在 - 它使用System.Security.Principal
命名空间中的SecurityIdentifier
来检查Sid是否有效。
public bool AccountExists(string name)
{
bool SidExists = false;
try
{
NTAccount Acct = new NTAccount(name);
SecurityIdentifier id = (SecurityIdentifier)Acct.Translate(typeof(SecurityIdentifier));
SidExists = id.IsAccountSid();
}
catch (IdentityNotMappedException)
{
//Oh snap.
}
return SidExists;
}
您可以在创建NTAccount
对象时指定域
NTAccount Acct = new NTAccount("SampleDomain", "SampleName");
编辑
在参考你的评论时,这对你有用吗? 没有检查它,可能必须在评估IsAccountSid()
方法之前处理可能的null返回...
public SecurityIdentifier AccountSID(string myDomain, string myAcct)
{
SecurityIdentifier id;
try
{
NTAccount Acct = new NTAccount(myDomain, myAcct);
id = (SecurityIdentifier)Acct.Translate(typeof(SecurityIdentifier));
}
catch (IdentityNotMappedException)
{
//Oh snap.
}
return id;
}
SecurityIdentifier AcctSID = AccountSID("ExampleDomain", "ExampleName");
if (AcctSID.IsAccountSid())
//Do Something
关于如何检查域中是否存在Windows用户帐户名的此问题的答案可能对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.