C#_验证域账户和密码

在C#中,你可以使用System.DirectoryServices.AccountManagement命名空间来验证域账户和密码。这个命名空间提供了一种简单的方法来验证用户的凭据。下面是一个示例代码,演示如何在C#中验证域账户和密码:

csharp 复制代码
using System;
using System.DirectoryServices.AccountManagement;

class Program
{
    static void Main()
    {
        Console.Write("Enter domain: ");// 域名,可使用Environment.UserDomainName获取当前域名
        string domain = Console.ReadLine();

        Console.Write("Enter username: ");// 账号
        string username = Console.ReadLine();

        Console.Write("Enter password: ");// 密码
        string password = Console.ReadLine();

        using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
        {
            bool isValid = context.ValidateCredentials(username, password);

            if (isValid)
            {
                Console.WriteLine("Login successful!");// 登录成功
            }
            else
            {
                Console.WriteLine("Login failed. Invalid username or password.");// 登录失败
            }
        }
    }
}

在上面的示例中,我们使用PrincipalContext类来建立与指定域的连接,并使用ValidateCredentials方法验证用户的凭据。如果提供的用户名和密码是有效的,则ValidateCredentials方法将返回true,否则返回false。

请注意,为了使用System.DirectoryServices.AccountManagement命名空间,你需要在项目中引用System.DirectoryServices.AccountManagement程序集。你可以在Visual Studio中右键单击项目 -> 添加 -> 引用 -> 搜索System.DirectoryServices.AccountManagement并添加它。

相关推荐
昂好的day6 小时前
固高运动控制卡实战(下):点位运动与直线/圆弧插补 API 详解
开发语言·c#
充值内卷6 小时前
[特殊字符] 自己动手做一个类 tldraw 的桌面白板:StepDraw 开源啦(C++ + WebView2 + Canvas)
开发语言·c++
raindayinrain6 小时前
c++对象模型--内存布局,多态,运行时类型识别
开发语言·c++
镜子AI6 小时前
镜子AI工程实践:用熵权法 + TOPSIS 做多方案选型排序(零依赖 Python)
开发语言·人工智能·python
估值探索者6 小时前
【Python量化组合管理实战 02】钱该怎么分?等权、波动率倒数与动态评分三种配权实测
java·开发语言·python·接口·股票数据api接口
西索斯coding6 小时前
Kimi K2.6 与 Qwen3.7 Max:跨文件修复评测与成本核算方法(2026)
开发语言·python·ai
wuyk5556 小时前
PyQt6-第10讲-PDF工具箱
python·microsoft·pdf·pyqt
从小白到软工6 小时前
5-2 从查表到控件:造按钮
c语言·开发语言·数据结构·经验分享·ai编程
迪康Defender7 小时前
PHP 高危漏洞应急分析:从风险原理到端点侧纵深防护
运维·开发语言·安全·自动化·php·运维开发·远程工作
2601_966949657 小时前
为什么不应该把 QuantDash API Key 直接写进公开代码仓库?从 Git 提交历史理解凭证泄露风险
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash