using System;
using System.DirectoryServices.AccountManagement;
class Program
{
static void Main(string[] args)
{
// 指定计算机名,如果为空则表示本地计算机
string computerName = null; // 本地计算机
// string computerName = "远程计算机名"; // 远程计算机
// 创建PrincipalContext对象,连接到本地计算机
using (PrincipalContext context = new PrincipalContext(ContextType.Machine, computerName))
{
// 创建用户对象
using (UserPrincipal user = new UserPrincipal(context))
{
// 设置用户属性
user.Name = "TestUser"; // 用户名
user.DisplayName = "Test User"; // 显示名称
user.Description = "This is a test user account."; // 描述
user.SetPassword("P@ssw0rd"); // 设置密码
user.UserCannotChangePassword = true; // 用户不能更改密码
user.PasswordNeverExpires = true; // 密码永不过期
// 保存用户
user.Save();
Console.WriteLine("用户账号创建成功!");
}
}
}
}