//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;
}
}
}
}