Link to home
Create AccountLog in
Avatar of SwamyN
SwamyN

asked on

Disabling local windows user account using c#.net

i want to disable a local windows user account using c#.net 2005 code.

i am able to create new account(local) using the folllowing code , but not able to disable.
i am getting the following error on line 10:
System.Runtime.InteropServices.COMException (0x8000500F): The directory property cannot be found in the cache

the code snippet:-

 private void AddUser(string strDoamin, string strLogin, string strPwd)
        {
           
            try
            {

                obDirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",Computer", "username", "password");
                DirectoryEntries entries = obDirEntry.Children;
                DirectoryEntry obUser = entries.Add(strLogin, "User");
                obUser.Properties["FullName"].Add("Amigo");
                object obRet = obUser.Invoke("SetPassword", strPwd);
 10:         obUser.Properties["useraccountcontrol"].Value  = ADS_UF_ACCOUNTDISABLE;
                obUser.CommitChanges();
                MessageBox.Show("User Account Crreated Successfully!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

pls help.
Avatar of sumix
sumix

To disable the account you need to change UserFlags property ('useraccountcontrol' exists for LDAP  DirectoryEntry, not for WINNT). In the value of this property you must set the flag ADS_UF_ACCOUNTDISABLE in UserFlags, so replace line 10 with:

                int valUsr = Convert.ToInt32(obUser.Properties["UserFlags"].Value);
                obUser.Properties["UserFlags"].Value = valUsr | ADS_UF_ACCOUNTDISABLE;

 Actually UserFlags is null (valUsr is always 0) for a newly created account, but i wrote a general approach.
Avatar of SwamyN

ASKER

after Replacing the above suggested line the following exception is thrown:-
System.Runtime.InteropServices.COMException
{"Exception from HRESULT: 0x8000500C"}

also the newly created local users: Convert.ToInt32(user.Properties["UserFlags"].Value) is 513
but setting  user.Properties["UserFlags"].Value = valUsr | ADS_UF_ACCOUNTDISABLE; throws the exception.
pls help me out.
So, if you comment out the line where you set UserFlags, the account is created all right?

You may check the value of UserFlags before commiting changes, if initial value is 513 after the OR operation it should be 515 (ADF_UF_ACCOUNTDISABLE is actually 2).

I cannot reproduce the error you mention, this is something related to Active Directory Services Interfaces (ADSI, see http://support.microsoft.com/kb/241981/en-us), maybe it is related to this ADSI version you have (check version like in http://support.microsoft.com/kb/247537).

Another try I can suggest is to set directly the value of UserFlags to 2:
         obUser.Properties["UserFlags"].Value =2;
Avatar of SwamyN

ASKER

thank you very much it solved my problem by using direct value.
Also when i use LDAP provider i am not able to add new user.

DirectoryEntry dsHelper = new UserAdmin("LDAP://"+ ddlDomain.SelectedItem.ToString(), txtUserNameI.Text, txtPasswordI.Text, AuthenticationTypes.Secure, ddlDomainI.SelectedText);

 NewUser = AD.Children.Add("CN=" + dsUser.Username + "", "user");

                    if (impersonateValidUser(this.LoginUsername, this.DomainName, this.loginPassword))
                    {
                        NewUser.CommitChanges();    
                    }

i am getting following error at  NewUser.CommitChanges();    line:-

UnAuthorisedAccessException

General access denied error

System.UnauthorizedAccessException was unhandled
  Message="General access denied error\r\n"
  Source="Active Directory"
  StackTrace:
       at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.SetInfo()
       at System.DirectoryServices.DirectoryEntry.CommitChanges()
       at DSHelper.UserAdmin.SaveUser(DSUser dsUser)
       at DSAdmin.Form1.AddNewUser()
       at DSAdmin.Form1.btnAddUser_Click(Object sender, EventArgs e)
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at DSAdmin.Program.Main()
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

pls help , i am using Domain Administrator User name & password, using which i can manually Login to server and add new user.
With LDAP you manage domain users only, the error you get shows that you don't have rights to create new users, maybe you should try first using the current logged in user (domain admin), without impersonation.
Avatar of SwamyN

ASKER

without impersonation if i login using domain admin everything works fine, but while impersonating it gives error as described above.
pls provide help for impersonation.
ASKER CERTIFIED SOLUTION
Avatar of sumix
sumix

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Forced accept.

Computer101
EE Admin