简而言之,我要做的是创建一个新用户,该用户可以登录。
我从各种来源中提取了代码,并试图对其进行简化。但是,我遇到了一些绊脚石。
当我调用 UserPrincipal.Save()
- 它给我一个错误
'The directory property cannot be found in the cache' with an exception type of.. 'COMExceptioncrossed a native/managed boundary'.
出于某种原因,当我直接运行我的程序(而不是通过 vs2010)时,它工作正常。所以我可以解决这个问题!
但我的主要问题是,尽管一切看起来都很好,但当我尝试登录时,它会显示消息“正在加载桌面”或其他任何内容,然后只是说“正在注销”。所以这几乎就像配置文件没有正确设置一样。
API“CreateProfile”的返回值不是 0,所以这可能导致了问题。
还有什么我需要做的吗?
我的代码是...
private void Run(string un, string pw)
{
UserPrincipal NewUP = CreateUser(un, pw);
AddGroup(NewUP, "Users");
AddGroup(NewUP, "HomeUsers");
CreateProfile(NewUP);
}
private UserPrincipal CreateUser(string Username, string Password)
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine, Environment.MachineName);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, Username);
if (up == null)
{
up = new UserPrincipal(pc, Username, Password, true);
up.UserCannotChangePassword = false;
up.PasswordNeverExpires = false;
up.Save(); // this is where it crashes when I run through the debugger
}
return up;
}
private void AddGroup(UserPrincipal Up, string GroupName)
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine, Environment.MachineName);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, GroupName);
if (!gp.Members.Contains(Up))
{
gp.Members.Add(Up);
gp.Save();
}
gp.Dispose();
}
private void CreateProfile(UserPrincipal Up)
{
int MaxPath = 240;
StringBuilder pathBuf = new StringBuilder(MaxPath);
uint pathLen = (uint)pathBuf.Capacity;
int Res = CreateProfile(Up.Sid.ToString(), Up.SamAccountName, pathBuf, pathLen);
}
最佳答案
奇怪的是,当它在服务器机器(即不是我的开发机器)上运行时,它工作正常。我感觉这与 Windows 7 或我的特定安装有关。
无论如何,感谢您的建议。
关于c# - 以编程方式创建 Windows 用户 c# .net(使用 PricinpalUser/CreateProfile),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9008742/