This code looks innocuous at first glance, but will not work for all filenames. If the filename contains characters like ', ", ;, or =, this code will create an invalid connection string and throw an exception.

The correct way to build connection strings is to use one of the DbConnectionStringBuilder classes. This class implements a dictionary of key-value pairs in the connection string. It has a ConnectionString property which assembles the instance’s contents into a usable connection string. Unlike the string concatenation shown above, this property will correctly escape all values.

In addition, each of the database clients included with the .Net framework (SQL, OleDB, ODBC, Oracle, and Entity Framework) have their own inherited ConnectionStringBuilder classes in their respective namespaces. These classes add type-safe properties for the the keys supported by their databases, and handle any special cases when generating the connection string.

As an added bonus, these classes implement ICustomTypeDescriptor, so they can be bound to a PropertyGrid to allow the end-user to edit the connection string. This can be seen in certain places in Visual Studio.