我有这个代码来创build一个本地的Windows用户
public static bool CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires) { try { PrincipalContext context = new PrincipalContext(ContextType.Machine); UserPrincipal user = new UserPrincipal(context); user.SetPassword(password); user.DisplayName = displayName; user.Name = username; user.Description = description; user.UserCannotChangePassword = canChangePwd; user.PasswordNeverExpires = pwdExpires; user.Save(); //now add user to "Users" group so it displays in Control Panel GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Users"); group.Members.Add(user); group.Save(); return true; } catch (Exception ex) { LogMessageToFile("error msg" + ex.Message); return false; } }
我试过这个在我的机器上工作正常。 但后来我把这个在Windows服务器上。 并试图在那里创build一个用户。
首先我得到了错误“一般访问被拒绝的错误”,所以我让用户pipe理员
但现在我得到错误“networkingpath没有find”
我怎么能解决这个错误..谢谢
我有一个非常类似的问题改变了第一行
PrincipalContext context = new PrincipalContext(ContextType.Machine, "127.0.0.1");
看看是否能解决你的问题。 并三重检查程序是否以管理员权限运行。
另一个问题可能是服务器具有密码复杂性要求,而传递给该函数的password
不符合这些要求。 如果您通过ASfas123@!fda
作为密码,问题是否消失?
我90%确定这是两个问题之一。
对于您的用户组不保存我不知道为什么。 从我的一个项目中,你正在做同样的事情。 我不能看到差异。
using (GroupPrincipal r = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users")) using (GroupPrincipal u = GroupPrincipal.FindByIdentity(context, "Users")) { //snip UserPrincipal user = null; try { if (userInfo.NewPassword == null) throw new ArgumentNullException("userInfo.NewPassword", "userInfo.NewPassword was null"); if (userInfo.NewPassword == "") throw new ArgumentOutOfRangeException("userInfo.NewPassword", "userInfo.NewPassword was empty"); //If the user already is in the list of existing users use that one. if (pr.ContainsKey(username)) { user = (UserPrincipal)pr[username]; user.Enabled = true; user.SetPassword(userInfo.NewPassword); } else { //create new windows user. user = new UserPrincipal(context, username, userInfo.NewPassword, true); user.UserCannotChangePassword = true; user.PasswordNeverExpires = true; user.Save(); r.Members.Add(user); r.Save(); u.Members.Add(user); u.Save(); } IADsTSUserEx iad = (IADsTSUserEx)((DirectoryEntry)user.GetUnderlyingObject()).NativeObject; iad.TerminalServicesInitialProgram = GenerateProgramString(infinityInfo); iad.TerminalServicesWorkDirectory = Service.Properties.Settings.Default.StartInPath; iad.ConnectClientDrivesAtLogon = 0; user.Save(); } catch(Exception e) { //snip } finally { if (user != null) { user.Dispose(); } } }
检查你是否没有启用UAC,或者你必须编写代码来提升你的应用程序权限。 然而这会重新启动你的应用程序