概述
之前做了个服务器主机助手,其中有个功能就是使用程序创建系统账户。本文实例讲述了C#创建windows系统用户的方法。分享给大家供大家参考。主要介绍了C#创建windows系统用户的方法,涉及C#操作用户名、密码、显示名称、描述、是否强制修改密码、密码是否过期等技巧。
主要代码实现
1、添加系统(域)用户
/// <summary>
/// 添加系统(域)用户
/// </summary>
/// <param name="strUserName"></param>
/// <param name="strPassword"></param>
/// <param name="strDescription"></param>
/// <param name="strGroup"></param>
/// <returns></returns>
public static bool AddUser(string strUserName, string strPassword, string strDescription, string strGroup)
{
using (DirectoryEntry AD = new DirectoryEntry(@"WinNT://" + Environment.MachineName + ",computer"))
{
try
{
DirectoryEntry User = null;
try
{
User = AD.Children.Find(strUserName, "user");//找到要删除的用户
if (User == null)
User = AD.Children.Add(strUserName, "user");
}
catch
{
User = AD.Children.Add(strUserName, "user");
}
User.Invoke("SetPassword", new object[] { strPassword }); // 密码
User.Properties["description"].Add(strDescription); //添加描述
//User.Invoke("Put", new object[] { "Description", strDescription });
User.Invoke("Put", "UserFlags", 66049); //密码永不过期
User.CommitChanges();
try
{
DirectoryEntry Group = AD.Children.Find(strGroup, "group");
if (strGroup != null)
Group.Invoke("Add", new object[] { User.Path.ToString() });
}
catch { }
}
catch (Exception ex)
{
EventLog.WriteEntry("autosystem", System.Reflection.MethodBase.GetCurrentMethod().Name.ToString() + ":" + ex.Message, EventLogEntryType.Error);
}
}
2、修改密码
/*
* 修改密码
*/
public static bool PwdModify(string strUserName, string strPassword)
{
using (DirectoryEntry AD = new DirectoryEntry(@"WinNT://" + Environment.MachineName + ",computer"))
{
try
{
DirectoryEntry User = AD.Children.Find(strUserName);
//修改密码
User.Invoke("SetPassword", new Object[] { strPassword });
User.CommitChanges();
}
catch {
return false;
}
}
return true;
3、 删除系统(域)用户
/// <summary>
/// 删除系统(域)用户
/// </summary>
/// <param name="strUserName">用户名</param>
/// <returns></returns>
public static bool RemoveUser(string strUserName)
{
try
{
using (DirectoryEntry AD = new DirectoryEntry(@"WinNT://" + Environment.MachineName + ",computer"))
{
DirectoryEntry User = AD.Children.Find(strUserName, "user");//找到要删除的用户
if (User != null)
AD.Children.Remove(User);
}
}
catch
{
return false;
}
return true;
4、判断组下的用户是否存在
/// <summary>
/// 判断组下的用户是否存在
/// </summary>
/// <param name="strGroupName">组名</param>
/// <param name="strUserName">用户名</param>
/// <returns></returns>
public static bool GroupSiteExists(string strGroupName, string strUserName)
{
try
{
using (DirectoryEntry AD = new DirectoryEntry(@"WinNT://" + Environment.MachineName + ",computer"))
{
DirectoryEntry Group = AD.Children.Find(strGroupName, "group");// 找到组
object members = Group.Invoke("Members", null);
foreach (object member in (System.Collections.IEnumerable)members)
{
//获取该组的每个成员
DirectoryEntry x = new DirectoryEntry(member);
if (strUserName == x.Name) //要移除的用户存在的话,则从该组中移除。
{
return true;
}
}
}
return false;
}
catch
{
return false;
}
}
}
希望本文所述对大家有所帮助。