c# 對windows使用者和組操作執行個體

來源:互聯網
上載者:User

複製代碼 代碼如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace JH.Framework.Security
{
///

/// 電腦使用者和組操作類
///

public class UserAndGroupHelper
{
private static readonly string PATH = "WinNT://" + Environment.MachineName;
///

/// 添加windows使用者
///

/// 使用者名稱
/// 密碼
/// 所屬組
/// 描述
public static void AddUser(string username, string password, string group, string description)
{
using (DirectoryEntry dir = new DirectoryEntry(PATH))
{
using (DirectoryEntry user = dir.Children.Add(username, "User")) //增加使用者名稱
{
user.Properties["FullName"].Add(username); //使用者全稱
user.Invoke("SetPassword", password); //使用者密碼
user.Invoke("Put", "Description", description);//使用者詳細描述
//user.Invoke("Put","PasswordExpired",1); //使用者下次登入需更改密碼
user.Invoke("Put", "UserFlags", 66049); //密碼永不到期
//user.Invoke("Put", "UserFlags", 0x0040);//使用者不能更改密碼s
user.CommitChanges();//儲存使用者
using (DirectoryEntry grp = dir.Children.Find(group, "group"))
{
if (grp.Name != "")
{
grp.Invoke("Add", user.Path.ToString());//將使用者添加到某組
}
}
}
}
}
///

/// 更改windows使用者密碼
///

/// 使用者名稱
/// 新密碼
public static void UpdateUserPassword(string username, string newpassword)
{
using (DirectoryEntry dir = new DirectoryEntry(PATH))
{
using (DirectoryEntry user = dir.Children.Find(username, "user"))
{
user.Invoke("SetPassword", new object[] { newpassword });
user.CommitChanges();
}
}
}
///

/// 刪除windows使用者
///

/// 使用者名稱
public static void RemoveUser(string username)
{
using (DirectoryEntry dir = new DirectoryEntry(PATH))
{
using (DirectoryEntry user = dir.Children.Find(username, "User"))
{
dir.Children.Remove(user);
}
}
}
///

/// 添加windows使用者組
///

/// 組名稱
/// 描述
public static void AddGroup(string groupName, string description)
{
using (DirectoryEntry dir = new DirectoryEntry(PATH))
{
using (DirectoryEntry group = dir.Children.Add(groupName, "group"))
{
group.Invoke("Put", new object[] { "Description", description });
group.CommitChanges();
}
}
}
///

/// 刪除windows使用者組
///

/// 組名稱
public static void RemoveGroup(string groupName)
{
using (DirectoryEntry dir = new DirectoryEntry(PATH))
{
using (DirectoryEntry group = dir.Children.Find(groupName, "Group"))
{
dir.Children.Remove(group);
}
}
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.