Introduction
Sometimes you may need your application to administer Windows user accounts by itself. Your application need to create OS user, modify its description, change password and perhaps delete the account when account is not needed any more. When I searched web sites for help (including msdn), I found various resources for this topic. But either they were not descriptive or with not enough source code. Some of them were in interpreted web scripts such as VBscript and Javascript. So, I collected work of all these great code contributors. And I have tried to modify these codes to suit your needs.
In this project, I have created a class called "SysUserManager". Main functions are written here. Another form is also created, from where these functions are called.
Namespaces used and steps to add them:
- System.DirectoryServices
- Choose "Project>Add Reference".
- Click on ".NET" tab.
- Select "System.DirectoryServices" from the list.
- Click on "Ok".
- Type "using System.DirectoryServices;" to import this namespace.
- Interop.ActiveDS and Interop.TSUSEREXLib (Only if you donot have them, for now, they are included in this application package)
- Download package "ADMODIFY.NET 2.1" from site:
http://www.gotdotnet.com/workspaces/workspace.aspx?id=f5cbbfa9-e46b-4a7a-8ed8-3e44523f32e2 - Unzip files to a local directory.
- From your solution, choose "Project>Add Reference".
- Click on "Browse" tab.
- From the location where you have unzipped the package "ADMODIFY", select Interop.ActiveDs.dll and Interop.TSUSEREXLib.dll files.
- Click on "OK".
- Type "using System.Runtime.InteropServices;" to use these files.
Using the code
We have to use "directoryentry" class for OS user management. For directoryentry constructor, we need to have a connection string. Format of this string is "PROTOCOL://HOSTNAME,COMPUTER". For "protocol", we can use "WinNT" protocol to manage local user accounts. For domain accounts, we use "LDAP" protocol. While creating user, we can set various properties for that user such as "password", "description", "groups" and "flags". For "flags", we use different constant values. At last, we must issue "commitchanges()" method to save user we created. If you are running this application in Terminal Server, you can also set the code to place initial program name to start in your code.
Algorithm for the code is as follows:
- Create a directory entry that represents host machine.
- Check whether user already exists or not.
- Create another directory entry for new user.
- Set new Password (using Invoke method) for this user.
- If description is given in application, set description as well.
- Set user options as set in application. (We are using constants here to represent hex values)
- Confirm changes by using "CommitChanges()" method.
- If group is provided, add user to group.
- Optional step (Only for TS Servers):
- Set "Initial Program" and "Working Directory" for the user.
Code:
try
{
string entryString = "WinNT://" + Environment.MachineName + ",computer";
DirectoryEntry dirEntry = new DirectoryEntry(entryString);
bool userFound = false;
try
{
if (dirEntry.Children.Find(username, "user") != null)
userFound = true;
}
catch
{
userFound = false;
}
if (!userFound)
{
DirectoryEntry newUser = dirEntry.Children.Add(username, "user");
newUser.Invoke("SetPassword", new object[] { password });
if(description.Trim()!="") newUser.Invoke("Put", new object[] {"Description", description});
int ADS_UF_PASSWD_CANT_CHANGE = 0x000000040;
int ADS_UF_DONT_EXPIRE_PASSWD = 0x00010000;
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;
if (!active)
{
int ADS_UF_ACCOUNTDISABLE = 0x0002;
combinedFlag = combinedFlag | ADS_UF_ACCOUNTDISABLE;
}
newUser.Invoke("Put", new Object[] { "userFlags", combinedFlag });
newUser.CommitChanges();
returnVal = "success";
if (defaultGroup.Trim() != "")
{
try
{
DirectoryEntry grpEntry = dirEntry.Children.Find(defaultGroup, "group");
if (grpEntry != null)
{
grpEntry.Invoke("Add", new object[] { newUser.Path.ToString() });
}
}
catch(Exception ex)
{
returnVal = _ErrorMsg = ex.Message;
}
}
try
{
DirectoryEntry userDE = dirEntry.Children.Find(username, "user");
ActiveDs.IADsUser iADsUser = (ActiveDs.IADsUser)userDE.NativeObject;
m_TsUser = (TSUSEREXLib.IADsTSUserEx)iADsUser;
m_TsUser.TerminalServicesInitialProgram = "Notepad.exe";
m_TsUser.TerminalServicesWorkDirectory = Environment.GetEnvironmentVariable("windir");
userDE.CommitChanges();
}
catch { }
}
else
{
returnVal = "User already exists!";
}
_ErrorMsg = "";
catch (Exception ex)
{
returnVal = _ErrorMsg = ex.Message;
}
Code to modify user settings, deleting user etc. is included in the project.