How to change sql server password expired with c # code?

When you use SqlConnection to connect to the MS Sql server, if the password has expired, you will receive the SqlException number: 18487 or 18488.

How can you change the user password in the code while trying to connect?

+4
source share
1 answer

Use the static method SqlConnection.ChangePassword () .

string original_dsn = "server=mysql.server.com,1433;database=pubdb;User Id={0};Password={1};"
string dsn = String.Format(original_dsn, username, password);

SqlConnection conn = new SqlConnection( dsn );
try
{
     conn.Open();
}
catch(SqlException e)
{
    if (e.Number == 18487 || e.Number == 18488)
           SqlConnection.ChangePassword(dsn, newpassword);
           // Try login again here with new password
    else
           MessageBox.Show(e.Message);
}
finally 
{
    conn.Close(); 
}
+4
source

All Articles