首页 > 系统相关 >c# 操作Windows帐户【转】

c# 操作Windows帐户【转】

时间:2022-11-08 08:55:35浏览次数:58  
标签:username 帐户 DirectoryEntry c# Windows localMachine user new string

1111

/// <summary>
/// 创建Windows帐户
/// </summary>
/// <param name="pathname"></param>
/// <returns></returns>
public static void CreateLocalUser(string username, string password, string description)
{
    DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
    var newUser = localMachine.Children.Add(username, "user");
    newUser.Invoke("SetPassword", new object[] { password });
    newUser.Invoke("Put", new object[] { "Description", description });
    newUser.CommitChanges();
    localMachine.Close();
    newUser.Close();
}

 

/// <summary>
/// 更改Windows帐户密码
/// </summary>
/// <param name="username"></param>
/// <param name="oldPwd"></param>
/// <param name="newPwd"></param>
public static void ChangeWinUserPasswd(string username, string oldPwd, string newPwd)
{
    DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
    DirectoryEntry user = localMachine.Children.Find(username, "user");
    object[] password = new object[] { oldPwd, newPwd };
    object ret = user.Invoke("ChangePassword", password);
    user.CommitChanges();
    localMachine.Close();
    user.Close();
}

 

/// <summary>
/// 判断Windows用户是否存在
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public static bool ExistWinUser(string username)
{
    try
    {
        using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
        {
            var user = localMachine.Children.Find(username, "user");
            return user != null;
        }
    }
    catch
    {
        return false;
    }
}

 

/// <summary>
/// 删除Windows用户
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public static bool DeleteWinUser(string username)
{
    try
    {
        using (DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
        {
            //删除存在用户
            var delUser = localMachine.Children.Find(username, "user");
            if (delUser != null)
            {
                localMachine.Children.Remove(delUser);
            }
        }
        return true;
    }
    catch
    {
        return false;
    }
}

 

/// <summary>
/// 启用/禁用windows帐户
/// </summary>
/// <param name="username"></param>
public static void Disable(string username, bool isDisable)
{
    var userDn = "WinNT://" + Environment.MachineName + "/" + username + ",user";
    DirectoryEntry user = new DirectoryEntry(userDn);
    user.InvokeSet("AccountDisabled", isDisable);
    user.CommitChanges();
    user.Close();
}

 

/// <summary>
    /// 给目录添加用户和权限
    /// </summary>
    /// <param name="pathname"></param>
    /// <param name="username"></param>
    /// <param name="qx"></param>
    public static void AddPathRights(string pathname, string username, FloderRights qx)
    {
        DirectoryInfo dirinfo = new DirectoryInfo(pathname);
        if ((dirinfo.Attributes & FileAttributes.ReadOnly) != 0)
        {
            dirinfo.Attributes = FileAttributes.Normal;
        }
        //取得访问控制列表
        DirectorySecurity dirsecurity = dirinfo.GetAccessControl();
        // string strDomain = Dns.GetHostName();
        switch (qx)
        {
            case FloderRights.FullControl:
                dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, AccessControlType.Allow));
                break;
            case FloderRights.Read:
                dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Read, AccessControlType.Allow));
                break;
            case FloderRights.Write:
                dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.Write, AccessControlType.Allow));
                break;
            default:
                dirsecurity.AddAccessRule(new FileSystemAccessRule(username, FileSystemRights.FullControl, AccessControlType.Deny));
                break;
        }
 
        dirinfo.SetAccessControl(dirsecurity);
 
        //取消目录从父继承
        DirectorySecurity dirSecurity = System.IO.Directory.GetAccessControl(pathname);
        dirSecurity.SetAccessRuleProtection(true, false);
        System.IO.Directory.SetAccessControl(pathname, dirSecurity);
 
        //AccessControlType.Allow允许访问受保护对象//Deny拒绝访问受保护对象
        //FullControl、Read 和 Write 完全控制,读,写
        //FileSystemRights.Write写入//Delete删除 //DeleteSubdirectoriesAndFiles删除文件夹和文件//ListDirectory读取
        //Modify读写删除-修改//只读打开文件和复制//
    }

 

文章来源:https://www.cnblogs.com/skynothing/

 

标签:username,帐户,DirectoryEntry,c#,Windows,localMachine,user,new,string
From: https://www.cnblogs.com/wxbug/p/16868501.html

相关文章

  • vscode常用配置
    {"editor.quickSuggestions":{"other":true,"comments":true,"strings":true},"editor.fontSize":16,"editor.wordWrap":"off",//永不......
  • ASP.NET Core教程-Configuration(配置)-Swagger
    更新记录转载请注明出处:2022年11月8日发布。2022年11月5日从笔记迁移到博客。注册服务在服务容器中注册服务,使用AddSwaggerGen()方法。builder.Services.AddSw......
  • 使用git时显示untracked files(未监控)解决办法
    gitstatus时除了显示自己修改的文件,还多了两个文件,显示如下:untrackedfiles:(use"gitadd<file>..."toincludeinwhatwillbecommited)bash.exe.stackdumpsh.exe.......
  • QUICKLISP
    QuicklispbetaQuicklisp isalibrarymanagerforCommonLisp.ItworkswithyourexistingCommonLispimplementationtodownload,install,andloadanyof o......
  • CF487E Tourists
    题意给定一张无向图,点有点权。每次可以修改一个点的点权,或者询问从\(a\)到\(b\)所有不经过重复点的路径上最小的点权是多少。Solution考虑一个点双,点双中任意两个点......
  • COHESION 衔接词
    1.表示强调still然而,仍然indeed事实上apparently显然oddlyenough奇怪的是ofcourse当然afterall毕竟significantly明显地;显著地interestingly有趣的是......
  • OpenGL ES EGL eglMakeCurrent
    目录一.EGL前言二.EGL绘制流程简介三.eglMakeCurrent函数简介1.eglMakeCurrent简介2.eglMakeCurrent实现3.eglMakeCurrent使用四.关于多个EGLContext......
  • webpack中配置CSS兼容性时报错 Failed to parse package.json data
      是因为在package.json中添加了注释正确webpack配置CSS兼容性的步骤:npmipostcss-loaderpostcss-preset-env-D/webpack.config.jsmodule:{    ru......
  • 计算机等级考试二级C语言上机题集(第96~100套)
    第96套1.程序填空题给定程序中,函数fun的功能是:将形参s所指字符串中的数字字符转换成对应的数值,计算出这些数值的累加和作为函数值返回。例如,形参s所指的字符串为:abs5def1......
  • Collection - Map & List & Set
    1.7-hashtable=数组+链表(>=)1.8=数组+链表+红黑树HashMap的容量-》数组的大小newHashMap():如果不写构造参数,默认大小是16,如果说写了初始容量:11,hashm......