Disabling local  windows user account using

Posted on 2007-09-29
Last Modified: 2013-11-26
i want to disable a local windows user account using 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)

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

pls help.
Question by:SwamyN
    LVL 12

    Expert Comment

    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 Comment

    after Replacing the above suggested line the following exception is thrown:-
    {"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.
    LVL 12

    Expert Comment

    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, maybe it is related to this ADSI version you have (check version like in

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

    Author Comment

    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))

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


    General access denied error

    System.UnauthorizedAccessException was unhandled
      Message="General access denied error\r\n"
      Source="Active Directory"
           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.
    LVL 12

    Expert Comment

    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 Comment

    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.
    LVL 12

    Accepted Solution

    LVL 1

    Expert Comment

    Forced accept.

    EE Admin

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
    For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK ( for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    This video is in connection to the article "The case of a missing mobile phone (". It will help one to understand clearly the steps to track a lost android phone.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now