C#通过Windows凭据获取域Active directory信息

C#通过Windows凭据获取域Active directory信息,c#,visual-studio-2013,active-directory,windows-authentication,C#,Visual Studio 2013,Active Directory,Windows Authentication,我一直在网上搜索活动目录和windows身份验证。我成功地从域广告中获取了用户信息,但我必须传递用户名和密码。因此,让我们来了解一下我的背景: 我有一个我已经设置了用户的域。每个用户都将使用其给定的凭据连接到域。因此,他们将登录到电脑,当他们打开VS 2013 C#应用程序时,它将检查用户是否存在于域中,如果用户存在,则返回广告信息。如果用户不存在,则显示登录页面以输入凭据。因为我可以让外部用户连接到我的域等 现在我无法使用用户的windows身份验证访问该广告,它在Search.FindOne

我一直在网上搜索活动目录和windows身份验证。我成功地从域广告中获取了用户信息,但我必须传递用户名和密码。因此,让我们来了解一下我的背景:

我有一个我已经设置了用户的域。每个用户都将使用其给定的凭据连接到域。因此,他们将登录到电脑,当他们打开VS 2013 C#应用程序时,它将检查用户是否存在于域中,如果用户存在,则返回广告信息。如果用户不存在,则显示登录页面以输入凭据。因为我可以让外部用户连接到我的域等

现在我无法使用用户的windows身份验证访问该广告,它在
Search.FindOne()上给了我一个未知错误

这就是我得到的错误

System.Runtime.InteropServices.COMException (0x80005000): Unknown error (0x80005000)
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
但是当我使用这个字符串时

string pathDomainName = "LDAP://MyDomain";
DirectoryEntry directoryEntry = new DirectoryEntry(pathDomainName, "Fred", "f12345!");
它可以工作,它会返回用户的所有广告,但我已经使用windows身份验证登录,为什么我要再次传递凭据?我只需要知道,如果用户存在于域中,那就是它


谢谢

如果您使用的是.NET 3.5及更高版本,您应该查看
System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。请在此处阅读所有相关内容:

基本上,您可以定义域上下文并在AD中轻松找到用户和/或组:

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }

    // or alternatively: get the currently logged in user
    UserPrincipal current = UserPrincipal.Current;

    .....
}
新的S.DS.AM使得在广告中与用户和群组进行互动变得非常容易

// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");

    if(user != null)
    {
       // do something here....     
    }

    // or alternatively: get the currently logged in user
    UserPrincipal current = UserPrincipal.Current;

    .....
}