You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用C#创建新用户、添加至Users组及配置远程权限的技术问题

我来帮你搞定这个Windows用户管理的任务,结合你给出的代码片段,我会补全剩余逻辑并把每个步骤讲清楚:

完整实现代码与说明

以下是满足你需求的完整C#代码,包含创建用户、添加到Users组、启用拨号权限和禁用远程控制的全部逻辑:

using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;

// 创建本地机器的上下文
using (PrincipalContext ctx = new PrincipalContext(ContextType.Machine))
{
    // 创建新用户:用户名newuser,密码password,启用状态true
    using (UserPrincipal newuser = new UserPrincipal(ctx, "newuser", "password", true))
    {
        // 保存用户到本地系统
        newuser.Save();

        // 查找Users组
        using (GroupPrincipal usersGroup = GroupPrincipal.FindByIdentity(ctx, "Users"))
        {
            if (usersGroup != null)
            {
                // 将新用户添加到Users组
                usersGroup.Members.Add(newuser);
                usersGroup.Save();
                Console.WriteLine("用户已成功添加到Users组");
            }
            else
            {
                Console.WriteLine("未找到Users组");
                return;
            }
        }

        // 获取用户的底层DirectoryEntry对象,用于修改高级属性
        using (DirectoryEntry userEntry = newuser.GetUnderlyingObject() as DirectoryEntry)
        {
            if (userEntry != null)
            {
                // 启用拨号远程网络权限:设置msNPAllowDialin属性为true
                userEntry.Properties["msNPAllowDialin"].Value = true;

                // 禁用远程控制:设置AllowRemoteControl属性为0(0=禁用,1=允许完全控制,2=允许查看)
                userEntry.Properties["AllowRemoteControl"].Value = 0;

                // 提交属性修改
                userEntry.CommitChanges();
                Console.WriteLine("已启用拨号权限并禁用远程控制");
            }
        }
    }
}
关键步骤说明
  • 创建用户:通过PrincipalContext指定本地机器上下文,UserPrincipal构造函数直接设置用户名、密码和启用状态,调用Save()完成创建
  • 添加到Users组:通过GroupPrincipal.FindByIdentity找到目标组,调用Members.Add()添加用户后保存组的修改
  • 修改高级属性:因为UserPrincipal没有直接暴露拨号权限和远程控制的属性,所以需要通过GetUnderlyingObject()获取底层的DirectoryEntry,手动修改对应的AD属性:
    • msNPAllowDialin:控制是否允许拨号远程连接,设为true启用
    • AllowRemoteControl:控制远程权限,设为0完全禁用远程控制
注意事项
  • 运行此代码需要管理员权限,否则会抛出权限不足的异常
  • 密码需要符合本地系统的密码策略(比如长度、复杂度要求),否则创建用户会失败
  • 确保项目中引用了System.DirectoryServices.AccountManagement和System.DirectoryServices程序集

内容的提问来源于stack exchange,提问作者Jeremy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:22:42