C# 检查广告中是否存在用户/电子邮件

C# 检查广告中是否存在用户/电子邮件,c#,asp.net,.net,active-directory,C#,Asp.net,.net,Active Directory,我在我的页面中有一个表单,用户可以通知其他用户的电子邮件或用户名。 在提交事件中,我需要检查Active Directory中是否存在此信息。 我怎么开这张支票?? 我明白了 我的页面 <asp:Label ID="lblUserAdd" runat="server" Font-Bold="true" Text="Add User - (Email or User Name)"></asp:Label> <br /> <asp:TextB

我在我的页面中有一个表单,用户可以通知其他用户的电子邮件或用户名。 在提交事件中,我需要检查Active Directory中是否存在此信息。 我怎么开这张支票?? 我明白了

我的页面

<asp:Label ID="lblUserAdd" runat="server" Font-Bold="true" Text="Add User - (Email or User Name)"></asp:Label>
    <br />
    <asp:TextBox ID="txtUserAdd" runat="server" Height="17px" Width="150px"></asp:TextBox>
    <asp:Label ID="lblError" runat="server" class="control-label" for="inputError" Visible="false">Input with error</asp:Label>
    <asp:Label ID="lblsuccess" runat="server" class="control-label" for="inputSuccess"
        Visible="false">Input with success</asp:Label>
    <asp:Button ID="btnAddUser" class="btn" runat="server" Font-Bold="true" Text="Add User"
        OnClick="btnSendUser_OnClick" />
    <br />
    <table id="tblUsers" class="table table-bordered">
        <asp:Label ID="lblUser" runat="server" Visible="false"></asp:Label>
    </table>

我为此创建了一个解决方案

protected void btnSendUser_OnClick(object sender, EventArgs e)
{
    string Loginfo = txtUserAdd.Text;
    string LoginInfo = txtUserAdd.Text;
    PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "x.com", "amsndruser", "XXX");
    UserPrincipal insUserPrincipal = UserPrincipal.FindByIdentity(insPrincipalContext, LoginInfo);
    if (insUserPrincipal == null)
    {
        lblError.Visible = true;
    }

    else
    {
        lblsuccess.Visible = true;
        lblUser.Visible = true;
        lblUser.Text = txtUserAdd.Text;
    }
}

我知道,这是一个非常古老的线程,但我一直在寻找解决方案,最后,这对我来说很有用:

using System.DirectoryServices.AccountManagement;

static bool UserExists(string UserName, string Email)
{
    PrincipalContext context = new PrincipalContext(ContextType.Domain, "YourDomain.xxx");
    UserPrincipal user = new UserPrincipal(context);
    user.SamAccountName = UserName;
    user.EmailAddress = Email;
    PrincipalSearcher ps = new PrincipalSearcher();
    ps.QueryFilter = user;
    var results = ps.FindAll().ToList();
    return results.Any();
}
using System.DirectoryServices.AccountManagement;

static bool UserExists(string UserName, string Email)
{
    PrincipalContext context = new PrincipalContext(ContextType.Domain, "YourDomain.xxx");
    UserPrincipal user = new UserPrincipal(context);
    user.SamAccountName = UserName;
    user.EmailAddress = Email;
    PrincipalSearcher ps = new PrincipalSearcher();
    ps.QueryFilter = user;
    var results = ps.FindAll().ToList();
    return results.Any();
}