I am writing a C# application which connects to a Microsoft SQL Server, chosen by the user, either using Integrated Security or a user-provided Username and Password to connect to the database.
Currently if the user inputs an incorrect password or is using a windows account which does not have permission to access the server, a SqlException is thrown when the SqlConnection is opened.
I wish to provide different feedback to the user dependent on whether a SqlException was thrown due to a failed login, or it was thrown because of another error, for example the server name being incorrect. Currently the only way of finding out why a SqlException was thrown is by looking at the message string, which isn't a very good solution. Is there a way of determining whether the username and password is correct before opening the SqlConnection, or finding out why a SqlException has been thrown?
Currently my connection string is Data Source=ServerName\SQLExpress;User=userName;Password=userPassword; or Data Source=ServerName\SQLExpress;Integrated Security=true; depending on the user's choice.
The code which opens the connection is:
const string ConnectionStringTemplate = "Data Source={0}\\SQLExpress;"; //Basic part of the connection string
const string UserLogInTemplate = "User={0};Password={1}"; //Template for adding user authentication
const string NoAuthString = "Integrated Security=true;"; //If no username/password provided use this
string connectionString;
connectionString = String.Format(ConnectionStringTemplate, serverName);
if (usesAuthentication)
{
connectionString += String.Format(UserLogInTemplate, userName, password);
}
else
{
connectionString += NoAuthString;
}
sqlcnn = new SqlConnection(connectionString);
sqlcnn.Open(); //SQLException occurs here if Password incorrect or server name wrong etc.