C# 如何更改已从C代码过期的sql server密码?

C# 如何更改已从C代码过期的sql server密码?,c#,sql-server,sqlconnection,C#,Sql Server,Sqlconnection,当您使用SqlConnection连接到MS Sql Server时,如果密码已过期,您将获得一个SqlException号码:18487或18488 在连接尝试期间,如何在代码中更改用户密码?使用静态方法 string original_dsn = "server=mysql.server.com,1433;database=pubdb;User Id={0};Password={1};" string dsn = String.Format(original_dsn, username, p

当您使用SqlConnection连接到MS Sql Server时,如果密码已过期,您将获得一个SqlException号码:18487或18488

在连接尝试期间,如何在代码中更改用户密码?

使用静态方法

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(); 
}