以编程方式创建Windows用户c#.net(使用PricinpalUser / CreateProfile)

2024-01-08

简而言之,我想做的是创建一个能够登录的新用户。

我从各种来源提取了代码,并尝试简化它。然而,我遇到了一些绊脚石。

当我打电话时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);
}

奇怪的是,当它在服务器计算机(即不是我的开发计算机)上运行时,它工作正常。我有一种感觉,这与 Windows 7 或我的特定安装有关。

不管怎样,谢谢你的建议。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式创建Windows用户c#.net(使用PricinpalUser / CreateProfile) 的相关文章

随机推荐