[英]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.