0

내가 가지고있는 AD에서 로컬 사용자 계정을 제거 다음 코드를 높이고 그런 사용자가 없습니다 경우에 그 예외를 잡기 피하기 위해 어떤 방법이 있나요예외를 발생시키지 않고 AD 항목을 찾는 방법은 무엇입니까?

try 
{ 
    string username = "MyUserName"; 

    using (DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost")) 
    { 
     DirectoryEntries entries = hostMachineDirectory.Children; 

     DirectoryEntry deUser = null; 
     try 
     { 
      deUser = entries.Find(username, "User"); 
     } 
     catch (COMException ex) 
     { 
      //Look for "no such user" exception 
      if ((uint)ex.ErrorCode != 0x800708ad) 
      { 
       throw ex; 
      } 
     } 

     if (deUser != null) 
      entries.Remove(deUser); 
     else 
      ShowMessageBoxError("No such user: " + username, MessageBoxIcon.Information); 
    } 
} 
catch (Exception ex) 
{ 
    ShowMessageBoxError(ex); 
} 

?

답변

1

.NET 3.5 이상인 경우 System.DirectoryServices.AccountManagement (S.DS.AM) 네임 스페이스를 확인해야합니다. 여기에 대한 모든 읽기 :

// set up context to your local machine only 
using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine)) 
{ 
    // find your user 
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username); 

    if(user != null) 
    { 
     // if user is found - remove it 
     user.Delete(); 
    } 
} 

을 : MSDN docs on System.DirectoryServices.AccountManagement

기본적으로

0

대신 DirectorySearcher를 사용할 수 있습니다. 필터를 설정하고 FindOne 메서드를 호출 한 다음 결과가 null인지 확인합니다.

관련 문제