We help IT Professionals succeed at work.

Disabling local  windows user account using c#.net

SwamyN
SwamyN asked
on
3,830 Views
Last Modified: 2013-11-26
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.
Comment
Watch Question

Commented:
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.

Author

Commented:
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.

Commented:
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;

Author

Commented:
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.

Commented:
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.

Author

Commented:
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.
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Forced accept.

Computer101
EE Admin

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.