如何在.net中以编程方式设置连接字符串?

我想以编程方式设置连接字符串,而绝对不更改任何配置文件/注册表项。


我有这段代码,但不幸的是,它抛出了“配置为只读”异常。


ConfigurationManager.ConnectionStrings.Clear();

string connectionString = "Server=myserver;Port=8080;Database=my_db;...";

ConnectionStringSettings connectionStringSettings = 

  new ConnectionStringSettings("MyConnectionStringKey", connectionString);

ConfigurationManager.ConnectionStrings.Add(connectionStringSettings);

编辑: 问题是我有从配置读取连接字符串的现有代码。因此,手动或通过资源设置配置字符串似乎不是有效的选项。我真正需要的是一种以编程方式修改配置的方法。


精慕HU
浏览 495回答 3
3回答

ABOUTYOU

我已经在博客中的帖子中对此进行了撰写。诀窍是使用反射来戳值,以获取对非公共字段(和方法)的访问。例如。var settings = ConfigurationManager.ConnectionStrings[ 0 ];var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );fi.SetValue(settings, false);settings.ConnectionString = "Data Source=Something";

蝴蝶不菲

我一直在寻找相同问题的答案,以允许用户通过选择本地SQL Server来更改单击一次应用程序中的连接字符串。下面的代码显示了一个用户窗体,该窗体与所有本地可用的SQL Server联系并允许他们选择一个。然后,它为该服务器构造一个连接字符串,并从表单上的变量返回它。然后,代码会修改配置文件并节省下来。string NewConnection = "";// get the user to supply connection detailsfrmSetSQLConnection frm = new frmSetSQLConnection();frm.ShowDialog();if (frm.DialogResult == DialogResult.OK){    // here we set the users connection string for the database    // Get the application configuration file.    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);    // Get the connection strings section.    ConnectionStringsSection csSection = config.ConnectionStrings;    foreach (ConnectionStringSettings connection3 in csSection.ConnectionStrings)    {        // Here we check for the preset string - this could be done by item no as well        if (connection3.ConnectionString == "Data Source=SQL204\\SQL2008;Initial Catalog=Transition;Integrated Security=True")        {             // amend the details and save             connection3.ConnectionString = frm.Connection;             NewConnection = frm.Connection;             break;        }    }    config.Save(ConfigurationSaveMode.Modified);    // reload the config file so the new values are available    ConfigurationManager.RefreshSection(csSection.SectionInformation.Name);    return clsDBMaintenance.UpdateDatabase(NewConnection))}

慕容3067478

解决此问题的另一种方法是直接对集合进行操作:var settings = ConfigurationManager.ConnectionStrings;var element = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);var collection = typeof(ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);element.SetValue(settings, false);collection.SetValue(settings, false);settings.Add(new ConnectionStringSettings("ConnectionStringName", connectionString));// Repeat above line as necessarycollection.SetValue(settings, true);element.SetValue(settings, true);
打开App,查看更多内容
随时随地看视频慕课网APP