Search code examples
c#connection-stringappsettings

Modifying connection string with variables


so my goal is to have a "settings form" which allows users to edit the connection string (by changing the database name / server location.

The reason for this is that it it needs to be able to changed when the server locations changes shortly by someone who may not have any C# experience (Front-End GUI).

I've created the connection strings in app.config but cannot find a way to assign variables inside the conn string that can be changed? I've created some application wide settings using the project properties. This is my app.config

<connectionStrings>
    <add name="xxxx"
        connectionString="Data Source=ServerIP;Initial Catalog=DBName;Persist Security Info=True;User ID=user;Password=password"
        providerName="System.Data.SqlClient" />
</connectionStrings>
<applicationSettings>
    <xxx.Properties.Settings>
        <setting name="ServerIP" serializeAs="String">
            <value />
        </setting>
        <setting name="DBName" serializeAs="String">
            <value />
        </setting>
    </xxx.Properties.Settings>
</applicationSettings>

Solution

  • One way to accomplish this would be to use placeholders ({0} and {1}) for those parts of the connection string in the config file, like so:

    Data Source={0};Initial Catalog={1};Persist Security Info=True;User ID=user;Password=password
    

    And then fill them in via string.Format when you read the connection string in your code, as in the following example. (Note: This assumes that you've added a reference to System.Configuration.dll, and that you've retrieved the application settings into two variables, serverIP and dbName.)

    using System.Configuration;
    
    ...
    
    string connectionString = string.Format(
        ConfigurationManager.ConnectionStrings["xxxx"].ConnectionString,
        serverIP,
        dbName);