?
Solved

Disabling local  windows user account using c#.net

Posted on 2007-09-29
10
Medium Priority
?
3,347 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.
0
Comment
Question by:SwamyN
  • 4
  • 3
8 Comments
 
LVL 12

Expert Comment

by:sumix
ID: 19983647
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.
0
 

Author Comment

by:SwamyN
ID: 19988944
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.
0
 
LVL 12

Expert Comment

by:sumix
ID: 19989289
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;
0
Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

 

Author Comment

by:SwamyN
ID: 19990812
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.
0
 
LVL 12

Expert Comment

by:sumix
ID: 19996613
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.
0
 

Author Comment

by:SwamyN
ID: 19997710
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.
0
 
LVL 12

Accepted Solution

by:
sumix earned 2000 total points
ID: 20004325
0
 
LVL 1

Expert Comment

by:Computer101
ID: 20294955
Forced accept.

Computer101
EE Admin
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses

850 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