我想使用 c# 代码创建一个 windows 用户。当登录用户具有管理员权限时,以下方法可以正常工作。它不适用于受限用户。注意我可以通过管理员用户的windows用户名和密码。基本上我想模仿。我试过模仿它没有用。我尝试将用户 namd 和密码传递给 processinfo。我收到错误“存根收到错误数据”。那么任何人都可以帮助我如何通过模拟使用 C# 代码创建 Windows 用户。
public static void CreateUser(string userName, string password, string description, string adminUserName, string adminPassword)
{
Process process = new Process();
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WorkingDirectory = Environment.SystemDirectory;
processInfo.FileName = "net.exe";
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardInput = true;
processInfo.RedirectStandardOutput = true;
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.Arguments = @" user " + userName + @" " + password + @" /ADD /ACTIVE:YES " +
@"/EXPIRES:NEVER /FULLNAME:" + userName + @" /PASSWORDCHG:NO /PASSWORDREQ:YES";
if (!string.IsNullOrEmpty(adminUserName))
{
processInfo.UserName = adminUserName;
processInfo.Password = WindowsSecurityHelper.GetSecuredString(adminPassword);
}
process.StartInfo = processInfo;
process.Start();
process.WaitForExit();
process.Close();
}
或者
public static void CreateUser(string userName, string password, string description, string userGroup = "Users")
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine, null);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, userGroup);
if (gp != null)
{
UserPrincipal u = new UserPrincipal(pc);
u.SetPassword(password);
u.Name = userName;
u.Description = description;
u.UserCannotChangePassword = true;
u.PasswordNeverExpires = true;
u.Save();
gp.Members.Add(u);
gp.Save();
}
}