c# - 读取 app.config 的 connectionStrings 元素

标签 c# configuration app-config configuration-files

我试图从我的 app.config 中读取连接字符串,但它只显示一个连接字符串,而且它也不在我的 app.config 中。

这是我的代码:

System.Diagnostics.Debugger.Break();

Configuration config = 
ConfigurationManager.OpenExeConfiguration(
                    AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

foreach (var connectionString in config.ConnectionStrings.ConnectionStrings)
    System.Diagnostics.Debug.Print(connectionString.ToString());

然后打印出来:

data source=.\SQLEXPRESS;Integrated Security=SSPI;
   AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true

当我期望它打印出自定义连接字符串到我在 app.config 文件中指定的数据库之一时。

更新

感谢大家花时间解决我的问题并尽力提供帮助。尽管你们所有人都说我可以简单地使用 ConfigurationManager.ConnectionStrings 或以这种方式访问​​任何其他小节,但我相信当我这样做时,配置是只读的。我无法对其进行任何更改,例如添加新的连接字符串或删除现有的连接字符串。我需要这样做。如果有办法在运行时修改配置文件,请告诉我。

最佳答案

它从您的 machine.config 中读取。 在<connectionStrings>之后在 app.config 中插入 <clear/>.

关于c# - 读取 app.config 的 connectionStrings 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4271166/

相关文章:

scala - 更新后 Unresolved 依赖 SBT 0.13.0

.net - 两个项目的 ClickOnce 部署各有自己的配置文件

c# - 为什么我的 ConnectionsStringCollection 条目比 app.config 中的 connection-Strings 部分多?

c# - 整数的字符串格式 c#

react-native - React Native 中最新的 doctor 命令的目的是什么

c# - 为什么可以从同一方法的覆盖版本调用方法的基本版本

java - 错误: Installation did not succeed.应用程序无法安装在Android Studio中

c# - 创建自定义配置

c# - 获取 ListView 子项的值

c# - 在 c# mvc 中对单选按钮进行分组