Format of the initialization string does not conform to specification starting at index

Short one.

You are letting your user connect to your trusted SQL Server (fairly common scenario J)

They are connecting using SQL Authentication (it is recommended to use Windows Authentication however) an intermittently the application throws an exception:

Unhandled Exception: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 42.

   at System.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue)

   at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey)

   at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules)

   at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)

   at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous)

   at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions)

   at System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value)

A common scenario here is that the user has provided a string termination character in the username or password and that character is not correctly escaped.

So, to illustrate:

            string cs = @"Data Source=server\instance;User=username;Password='password;Initial Catalog=database";

            using (SqlConnection con = new SqlConnection(cs))

            {

                try

                {

                    con.Open();

                    Console.WriteLine("We are connected...");

                    con.Close();

                }

                catch (Exception ex)

                {

                    Console.WriteLine(ex);

                }

            }

Will give the exception above.

So either escape the ‘ correctly (Password=\'password) or do not allow the single quote.