Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change password to user account, by c# code?

Tags:

c#

how to change password to user account, by c# code?

like image 776
sari k Avatar asked Feb 04 '23 00:02

sari k


2 Answers

Here is a simpler way to do this, however you will need to reference System.DirectoryServices.AccountManagement from .Net 4.0

namespace PasswordChanger
{
    using System;
    using System.DirectoryServices.AccountManagement;

    class Program
    {
        static void Main(string[] args)
        {
            ChangePassword("domain", "user", "oldpassword", "newpassword");
        }

        public static void ChangePassword(string domain, string userName, string oldPassword, string newPassword)
        {
            try
            {
                using (var context = new PrincipalContext(ContextType.Domain, domain))
                using (var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName))
                {
                    user.ChangePassword(oldPassword, newPassword);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}
like image 141
Paul Avatar answered Feb 05 '23 19:02

Paul


Using active directory:

// Connect to Active Directory and get the DirectoryEntry object.
// Note, ADPath is an Active Directory path pointing to a user. You would have created this
// path by calling a GetUser() function, which searches AD for the specified user
// and returns its DirectoryEntry object or path. See http://www.primaryobjects.com/CMS/Article61.aspx
DirectoryEntry oDE;
oDE = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);

try
{
   // Change the password.
   oDE.Invoke("ChangePassword", new object[]{strOldPassword, strNewPassword});
} 
catch (Exception excep)
{
   Debug.WriteLine("Error changing password. Reason: " + excep.Message);
}

Here you have example to change it in the local user account:

http://msdn.microsoft.com/en-us/library/ms817839

Other alternative could be using interoperability and call unmanaged code: netapi32.dll

http://msdn.microsoft.com/en-us/library/aa370650(VS.85).aspx

like image 44
Daniel Peñalba Avatar answered Feb 05 '23 19:02

Daniel Peñalba