Modifying connection string with variables

╄→尐↘猪︶ㄣ 提交于 2019-12-12 12:28:12

问题


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>

回答1:


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);


来源:https://stackoverflow.com/questions/26247349/modifying-connection-string-with-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!