2010-10-01 31 views
2

我正在使用這種在當前域中查找用戶的簡單方法,該方法適用於「存在」的所有用戶,但我無法找到任何方式來確定用戶是否存在。如何確定「DirectoryEntry」是否找到我的用戶?

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) 

回答

5

這是更好地使用的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,因此需要如上所示進行處理。

+0

+1,因爲這似乎是最完整的答案。 – LamonteCristo 2010-10-05 13:38:13

+0

...(並感謝編輯使其更加完整) – LamonteCristo 2010-11-12 19:21:53

0

您是否在尋找特定用戶或所有用戶?

我有一個應用程序通過檢查帳戶名來檢查用戶是否在場 - 它在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"); 

編輯

在提及你的評論可以指定域,將這項工作的嗎? Didnt檢查,可能需要處理evaulating的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 
+0

我正在尋找一個特定的用戶。我的目標是獲得SID以將其添加到SSAS角色 – LamonteCristo 2010-10-02 00:21:35

0

我認爲,如果你的DirectoryEntry對象指向現有的AD條目使用靜態已存在方法來檢查一個簡單的方法。

所以,你的代碼可能是這樣的:

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 

當然,你可以省略存在變數。我用它只是爲了使聲明更清楚。

相關問題