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

标签 c# .net windows security windows-7

简而言之,我要做的是创建一个新用户,该用户可以登录。

我从各种来源中提取了代码,并试图对其进行简化。但是,我遇到了一些绊脚石。

当我调用 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/

相关文章:

C# 将一维数组转换为二维

c# - 如何在特定 <div> 标记中的另一个 aspx 页面中加载一个 aspx 页面

c# - ICommunicationObject.State 不起作用?

.net - 向 MembershipProvider 添加额外的属性

windows - 什么是 Teredo 隧道伪接口(interface)?

windows - 在 Windows 上使用 msysgit 设置 Git 服务器

C# 通过实现的显式转换获取转换异常

c# - 需要想法来设计我的网格。 asp.net(c#) GridView

c# - 如何使用 XSLT 将 XML 转换为无效的 XML?

.net - 使用 Windows Crypto API 的 Windows 2000 和 Windows 2003 RC2 加密/解密?