Create And Delete Windows user using .net windows application

Sunday 21 June 2015

Create And Delete Windows user using .net windows application

Create And Delete Windows user using .net windows application 


  1. Take two button Create and Delete user on windows form 
  2. one class SysUserManager

  private void btnCreateUser_Click(object sender, EventArgs e)
        {
            string username = "eCORD";//txtusername.Text.Trim();
            string password = "$e(0rd%15#";// txtpassword.Text.Trim();
            string description = "Scan Machine User Creation";//txtdescription.Text.Trim();
            string defaultgroup = "Users";//cmbGroup.Text;

            if (username.Length == 0 || defaultgroup.Length == 0)
            {
                MessageBox.Show("Required Information Not Sufficient!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string returnVal=SysUserManager.CreateWinUser(username, password, description,
               true,true,true, defaultgroup);
            if(returnVal=="success")
                MessageBox.Show("User successfully created!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show(returnVal, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnModifyUser_Click(object sender, EventArgs e)/// not used
        {
            string username = "eCORD";//txtusername.Text.Trim();
            string password = "$e(0rd%15#";// txtpassword.Text.Trim();
            string description = "Scan Machine User Creation";//txtdescription.Text.Trim();
            string defaultgroup = "Users";//cmbGroup.Text;

            if (username.Length == 0 || defaultgroup.Length == 0)
            {
                MessageBox.Show("Required Information Not Sufficient!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            bool returnVal = SysUserManager.ModifyUser(username, this.changePassword, password, description,
                true, true,true,  this.changeGroup, defaultgroup, "");
            if (returnVal)
                MessageBox.Show("User successfully modified!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show(SysUserManager._ErrorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            string username = "eCORD";//txtusername.Text.Trim();
           
            if (username.Length == 0)
            {
                MessageBox.Show("Required Information Not Sufficient!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            bool returnVal = SysUserManager.DeleteUser(username);
            if (returnVal)
                MessageBox.Show("User successfully deleted!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show(SysUserManager._ErrorMsg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

       

Create a class : SysUserManager.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.DirectoryServices;
using System.Collections; 
using System.Runtime.InteropServices;
using System.Data;



/**  
 * Title System User Management
 * Description This class is used for manipulating local windows user accounts
 * Author    Ritesh Singh
 *   
 */
namespace OSUserManagement
{
    /**< Class that manipulates local windows user accounts */
    public class SysUserManager
    {
        public static String _ErrorMsg = ""; /*! Variable that holds error information */
        private static TSUSEREXLib.IADsTSUserEx m_TsUser;

        /*!Function: This Function Creates System User*/
        public static string CreateWinUser(string username, string password,
            string description, bool active, bool cannotchangepassword, bool passwordneverexpires, string defaultGroup)
        {
            String returnVal = "success";

            try
            {
                //Initiate DirectoryEntry Class To Connect Through WINNT Protocol
                string entryString = "WinNT://" + Environment.MachineName + ",computer";
                DirectoryEntry dirEntry = new DirectoryEntry(entryString);              
                
                    
                //Search If Specified User Already Exists
                bool userFound = false;

                try
                {
                    if (dirEntry.Children.Find(username, "user") != null)
                        userFound = true;
                }
                catch
                {
                    userFound = false;
                }

                
                if (!userFound) //If User Not Found In System
                {
                    DirectoryEntry newUser = dirEntry.Children.Add(username, "user"); //Add user
                    newUser.Invoke("SetPassword", new object[] { password }); //Set password
                    
                    if(description.Trim()!="") newUser.Invoke("Put", new object[] {"Description", description});

                    
                    //Flags
                    //1. User cannot change password
                    int ADS_UF_PASSWD_CANT_CHANGE = 0x000000040;
                    //newUser.Invoke("Put", new Object[] { "userFlags", ADS_UF_PASSWD_CANT_CHANGE });

                    //2. Password Never Expires
                    int ADS_UF_DONT_EXPIRE_PASSWD = 0x00010000;
                    //newUser.Invoke("Put", new Object[] { "userFlags", ADS_UF_DONT_EXPIRE_PASSWD });

                    int combinedFlag=0;
                    if(cannotchangepassword&&passwordneverexpires) 
                        combinedFlag = ADS_UF_DONT_EXPIRE_PASSWD | ADS_UF_PASSWD_CANT_CHANGE;
                    else if(cannotchangepassword)
                        combinedFlag = ADS_UF_PASSWD_CANT_CHANGE;
                    else if(passwordneverexpires)
                        combinedFlag = ADS_UF_DONT_EXPIRE_PASSWD;

                    //3. Account Disabled
                    if (!active)
                    {
                        int ADS_UF_ACCOUNTDISABLE = 0x0002;
                        combinedFlag = combinedFlag | ADS_UF_ACCOUNTDISABLE;
                    }

                    
                    newUser.Invoke("Put", new Object[] { "userFlags", combinedFlag });
                    
                    //Commit Changes
                    newUser.CommitChanges();

                    returnVal = "success";

                    //If defaultGroup Is Provided, Add New User To This Group
                    if (defaultGroup.Trim() != "")
                    {
                        try
                        {
                            DirectoryEntry grpEntry = dirEntry.Children.Find(defaultGroup, "group");
                            if (grpEntry != null)
                            {
                                //Add User To defaultGroup
                                grpEntry.Invoke("Add", new object[] { newUser.Path.ToString() });
                            }
                        }
                        catch(Exception ex)
                        {
                            returnVal = _ErrorMsg = ex.Message;
                        }

                    }

                    try
                    {
                        DirectoryEntry userDE = dirEntry.Children.Find(username, "user");

                        //For Terminal Settings (Only If this is Terminal Server)
                        ActiveDs.IADsUser iADsUser = (ActiveDs.IADsUser)userDE.NativeObject;
                        m_TsUser = (TSUSEREXLib.IADsTSUserEx)iADsUser;

                        m_TsUser.TerminalServicesInitialProgram = "Notepad.exe"; //For Example
                        m_TsUser.TerminalServicesWorkDirectory = Environment.GetEnvironmentVariable("windir");

                        userDE.CommitChanges();
                    }
                    catch {  }
                   

                } 
                else //If User Already Exists
                {
                    returnVal = "User already exists!";
                } //End of - if (!userFound)

                _ErrorMsg = "";
               
            }
            catch (Exception ex)
            {
                returnVal = _ErrorMsg = ex.Message;
            }


            return returnVal;
        }

        /*!Function: Enables/Disables Specified User Account*/
        public static bool EnableDisableUser(string username, bool active)
        {
            bool returnVal = false;

            try
            {
                //Initiate DirectoryEntry Class To Connect Through WINNT Protocol
                string entryString = "WinNT://" + Environment.MachineName + ",computer";
                DirectoryEntry dirEntry = new DirectoryEntry(entryString);

                DirectoryEntry osuser = dirEntry.Children.Find(username, "user");

                
                
                if (osuser == null)
                {
                    _ErrorMsg = "Such OS user not found.";
                }
                else
                {
                    //Flags
                    //First Normal Account
                    int ADS_UF_NORMAL_ACCOUNT = 512;
                    int combinedFlag = ADS_UF_NORMAL_ACCOUNT; //(int)userFlags;


                    //1. User cannot change password
                    int ADS_UF_PASSWD_CANT_CHANGE = 0x000000040;

                    //2. Password Never Expires
                    int ADS_UF_DONT_EXPIRE_PASSWD = 0x00010000;

                    combinedFlag = ADS_UF_NORMAL_ACCOUNT | ADS_UF_DONT_EXPIRE_PASSWD | ADS_UF_PASSWD_CANT_CHANGE;

                    //3. Account Disabled
                    if (!active)
                    {
                        int ADS_UF_ACCOUNTDISABLE = 0x0002;
                        combinedFlag = combinedFlag | ADS_UF_ACCOUNTDISABLE;
                    }

                    osuser.Invoke("Put", new Object[] { "userFlags", combinedFlag });

                    //Commit Changes
                    osuser.CommitChanges();

                    returnVal = true;
                    _ErrorMsg = "";
                }

            }
            catch (Exception exe)
            {
                _ErrorMsg = exe.Message;
            }

            return returnVal;
        }

        /*!Function: Sets Password of Specified User*/
        public static bool SetUserPassword(string username, string newpassword)
        {
            bool returnVal = false;

            try
            {
                //Initiate DirectoryEntry Class To Connect Through WINNT Protocol
                string entryString = "WinNT://" + Environment.MachineName + ",computer";
                DirectoryEntry dirEntry = new DirectoryEntry(entryString);

                DirectoryEntry osuser=dirEntry.Children.Find(username, "user");

                if (osuser == null)
                {
                    _ErrorMsg = "Such OS user not found.";
                }
                else
                {
                    osuser.Invoke("SetPassword", newpassword);
                    osuser.CommitChanges();

                    returnVal = true;
                    _ErrorMsg = "";
                }
                
            }
            catch (Exception exe)
            {
                _ErrorMsg = exe.Message;
            }

            return returnVal;
        }

        /*!Function: Changes the OS Password.*/
        public static bool ChangePassword(string userName, string newPassword) 
        {
            try
            {
                string entryString = "WinNT://" + Environment.MachineName + ",computer";
                DirectoryEntry dirEntry = new DirectoryEntry(entryString);
                DirectoryEntry osUser = dirEntry.Children.Find(userName, "user");
                osUser.Invoke("SetPassword", newPassword);
                osUser.CommitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /*!Function: Modifies Specified User Account Settings*/
        public static bool ModifyUser(string username, bool changepassword, string newpassword, string description,
            bool active, bool cannotchangepassword,bool passwordneverexpires, bool isGroupChanged, string newGroup, string oldGroup)
        {
            bool returnVal = false;

            try
            {
                //Initiate DirectoryEntry Class To Connect Through WINNT Protocol
                string entryString = "WinNT://" + Environment.MachineName + ",computer";
                DirectoryEntry dirEntry = new DirectoryEntry(entryString);

                DirectoryEntry osUser = dirEntry.Children.Find(username, "user"); 
                
                if (osUser == null)
                {
                    _ErrorMsg = "Such OS user not found.";
                }
                else
                {
                    if (changepassword)
                        osUser.Invoke("SetPassword", newpassword);
                    if (isGroupChanged && (oldGroup != newGroup))
                    {
                        DirectoryEntry grpEntry = null;

                        //first add the user to the new group
                        grpEntry = dirEntry.Children.Find(newGroup, "group");
                        if (grpEntry != null)
                        {
                            grpEntry.Invoke("Add", new object[] { osUser.Path });
                        }
                        //then remove from the old group 
                        //this portion hasn't been completed
                       
                        
                    }
                }                
                //Object desc=osuser.InvokeGet("Description"); //Old Description
                osUser.Invoke("Put", new object[] { "Description", description });

                //User Flags
                Object userFlags = osUser.InvokeGet("userFlags");

                //Flags
                //First Normal Account
                int ADS_UF_NORMAL_ACCOUNT = 512;
                int combinedFlag = ADS_UF_NORMAL_ACCOUNT; 


                //1. User cannot change password
                int ADS_UF_PASSWD_CANT_CHANGE = 0x000000040;

                //2. Password Never Expires
                int ADS_UF_DONT_EXPIRE_PASSWD = 0x00010000;


                if (cannotchangepassword && passwordneverexpires)
                    combinedFlag = combinedFlag | ADS_UF_DONT_EXPIRE_PASSWD | ADS_UF_PASSWD_CANT_CHANGE;
                else if (cannotchangepassword)
                    combinedFlag = combinedFlag | ADS_UF_PASSWD_CANT_CHANGE;
                else if (passwordneverexpires)
                    combinedFlag = combinedFlag | ADS_UF_DONT_EXPIRE_PASSWD;

                //combinedFlag = ADS_UF_NORMAL_ACCOUNT | ADS_UF_DONT_EXPIRE_PASSWD | ADS_UF_PASSWD_CANT_CHANGE;

                //3. Account Disabled
                if (!active)
                {
                    int ADS_UF_ACCOUNTDISABLE = 0x0002;
                    combinedFlag = combinedFlag | ADS_UF_ACCOUNTDISABLE;
                }



                osUser.Invoke("Put", new Object[] { "userFlags", combinedFlag });

                //Commit Changes
                osUser.CommitChanges();

                returnVal = true;
                _ErrorMsg = "";
            }


            catch (Exception exe)
            {
                _ErrorMsg = exe.Message;
            }

            return returnVal;
        }

        /*!Function: Deletes Specified User Account*/
        public static bool DeleteUser(string username)
        {
            bool returnVal = false;

            try
            {
                //Initiate DirectoryEntry Class To Connect Through WINNT Protocol
                string entryString = "WinNT://" + Environment.MachineName + ",computer";
                DirectoryEntry dirEntry = new DirectoryEntry(entryString);

                DirectoryEntry osuser = dirEntry.Children.Find(username, "user");

                if (osuser == null)
                {
                    _ErrorMsg = "Such OS user not found.";
                }
                else
                {
                    dirEntry.Children.Remove(osuser);

                    returnVal = true;
                    _ErrorMsg = "";
                }

            }
            catch (Exception exe)
            {
                _ErrorMsg = exe.Message;
            }

            return returnVal;

        }
    }
}