Chris (who I meet down at SC Code Camp 2006) left a comment on my C# connection string validation code pointing out some flaws in my code. He suggested playing with System.Data.SqlClient.SqlConnectionStringBuilder.
I redid the code to take advantage of this helper class. Here is the updated version of the code. Note that I only validate Data Source, Initial Catalog, User ID and Password because that is the only thing our software uses right now.
public static bool IsValidSQLConnectionString(string cn)
{
bool rv = true;
try
{
SqlConnectionStringBuilder sqlSB = new SqlConnectionStringBuilder();
sqlSB.ConnectionString = cn;
if (string.IsNullOrEmpty(sqlSB.DataSource))
{
throw new ApplicationException("Data Source missing");
}
if (string.IsNullOrEmpty(sqlSB.InitialCatalog))
{
throw new ApplicationException("Initial Catalog missing");
}
if (string.IsNullOrEmpty(sqlSB.UserID))
{
throw new ApplicationException("User ID missing");
}
if (string.IsNullOrEmpty(sqlSB.Password))
{
throw new ApplicationException("Password missing");
}
}
catch (Exception)
{
rv = false;
}
return rv;
}