现在的位置: 首页 > 综合 > 正文

C# 通过DirectoryService 创建修改用户和组

2018年04月07日 ⁄ 综合 ⁄ 共 1612字 ⁄ 字号 评论关闭

//WinNT用户管理
using System;
using System.DirectoryServices;
namespace Host.AdminManager.Inc
{
public class WindwosUser
{
//创建NT用户
//传入参数:Username要创建的用户名,Userpassword用户密码,Path主文件夹路径
public static bool CreateNTUser(string Username,string Userpassword,string Path)
{
DirectoryEntry obDirEntry = null;
try
{
obDirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry obUser = obDirEntry.Children.Add(Username, "User"); //增加用户名
obUser.Properties["FullName"].Add(Username); //用户全称
obUser.Invoke("SetPassword", Userpassword); //用户密码
obUser.Invoke("Put", "Description","Test User from .NET");//用户详细描述
//obUser.Invoke("Put","PasswordExpired",1); //用户下次登录需更改密码
obUser.Invoke("Put","UserFlags",66049); //密码永不过期
obUser.Invoke("Put","HomeDirectory",Path); //主文件夹路径
obUser.CommitChanges();//保存用户
DirectoryEntry grp = obDirEntry.Children.Find("Users", "group");//Users组
if(grp.Name!="")
{
grp.Invoke("Add",obUser.Path.ToString());//将用户添加到某组
}
return true;
}
catch
{
return false;
}
}
//删除NT用户
//传入参数:Username用户名
public static bool DelNTUser(string Username)
{
try
{
DirectoryEntry obComputer = new DirectoryEntry("WinNt://" + Environment.MachineName);//获得计算机实例
DirectoryEntry obUser = obComputer.Children.Find(Username,"User");//找得用户
obComputer.Children.Remove(obUser);//删除用户
return true;
}
catch
{
return false;
}
}

//修改NT用户密码
//传入参数:Username用户名,Userpassword用户新密码
public static bool InitNTPwd(string Username,string Userpassword)
{
try
{
DirectoryEntry obComputer = new DirectoryEntry("WinNt://" + Environment.MachineName);
DirectoryEntry obUser = obComputer.Children.Find(Username,"User");
obUser.Invoke("SetPassword", Userpassword);
obUser.CommitChanges();
obUser.Close();
obComputer.Close();
return true;
}
catch
{
return false;
}
}
}
}

抱歉!评论已关闭.