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("用戶賬號創建成功!");
}
}
}
}