3

C#コードのweb.configで接続文字列を動的に設定しようとしています:

ConfigurationManager.ConnectionStrings["ServerConnection"].ConnectionString = "blah";

しかし、それは私がそれを行うことを許可せず、次のエラーをスローします:

The configuration is read only.

注:可能であれば、実際にはweb.configに保存したくありません。動的にメモリに設定するだけです。

4

2 に答える 2

2
var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["ServerConnection"].ConnectionString = "Data Source=...";
configuration.Save();

実際の web.config を変更したくない場合は、次を使用できます。

using(OleDbConnection conn = new OleDbConnection("Type here your connection string"))
{
     // Execute my code
}

または、一部のデータを保持したい場合は、接続文字列の値を別の文字列にコピーしてから変更を加えることができます..

string myNewConnectionString = ConfigurationManager.ConnectionStrings["ServerConnection"].ConnectionString;
myNewConnectionString.Replace("Data Source=Development", "Data Source=Production");
于 2012-12-06T19:07:44.653 に答える
0

私が間違っている場合は修正してください。ただし、ConfigurationManager 構成は読み取り専用であることを確信しています。web.configfor を変更することで設定を変更できますapp.config

動的に設定するためのものではありません。

于 2012-12-06T19:01:52.757 に答える