简体   繁体   中英

Temporarily change connection string in app.config

I have a DB2 environment, to which I would like to connect with Entity Framework. To do that, I need a connection string which looks like this, in the app.config file:

<connectionStrings>
  <add name="DB2Connect" connectionString="Database=my_db; UID=Username; PWD=Password;"/>
</connectionStrings>

It doesn't seem like a good idea to have a password hardcoded into the app.config file, so I would like to replace it at run time, but only temporarily! The temporary part, is what is causing me trouble. I have successfully managed to replace the connection string, with the following code, but it's no good when the password remains in the the app.config file, afterwards:

private static void SaveConnectionString(string name, string connectionString)
{
    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
    connectionStringsSection.ConnectionStrings[name].ConnectionString = connectionString;
    config.Save();
    ConfigurationManager.RefreshSection("connectionStrings");
}

不知道我在这里是否回答了不同的问题,但是如果您在构建发行版本时正在寻找一种解决方案,以解决无/不同连接字符串的问题,则可以查看: https : //marketplace.visualstudio.com/items?itemName = vscps.SlowCheetah-XMLTransforms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM