简而言之,我想做的是创建一个能够登录的新用户。
我从各种来源提取了代码,并尝试简化它。然而,我遇到了一些绊脚石。
当我打电话时UserPrincipal.Save()
- 它给了我一个错误
'在缓存中找不到目录属性'
异常类型..“COMExceptioncrossed a native/托管边界”。
由于某种原因,当我直接运行我的程序(而不是通过 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);
}