读取您的app.config文件中的connectionStrings元素

5

我正在尝试从我的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或以这种方式访问任何其他子部分,但我相信当我这样做时,配置是只读的。我不能进行任何更改,比如添加一个新的连接字符串或删除一个现有的连接字符串。而我需要这样做。请告诉我是否有一种方法可以在运行时修改配置文件。
6个回答

2

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


2

你为什么要使用 OpenExeConfiguration 来打开配置文件呢?如果是作为项目的一部分创建的 app.config 文件,那么你只需要使用 ConfigurationManager.ConnectionStrings


2

ConfigurationManager.ConnectionStrings["ConnectionStringName"]应该可以完成它,除非它被存储为appSetting。

在这种情况下,它将位于ConfigurationManager.AppSettings["SettingName"]中。


1

如果你想编辑ConnectionStrings(或者app.config中的任何部分),你需要使用Configuration对象的GetSection()方法返回的对象。

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection csSettings = config.GetSection("connectionStrings") as ConnectionStringsSection;
if(csSettings != null)
{
    // examples of removing all settings, adding a new one and removing it
    csSettings.ConnectionStrings.Clear();
    csSettings.ConnectionStrings.Add(new ConnectionStringSettings("myCS", "<connectionString>"));
    csSettings.ConnectionStrings.Remove("myCS");
    // save the changes
    config.Save(ConfigurationSaveMode.Modified);
}

根据我的经验,OpenExeConfiguration(string)存在一个bug,这意味着它总是打开你的app.config文件。如果要从文件名打开配置文件,需要使用OpenMappedExeConfiguration()。

0

我写了一个小的控制台应用程序(包含在一个较大的 Web 应用程序解决方案中),遇到了完全相同的问题 - 似乎我的 app.config 已经不再被识别,而我得到的唯一连接字符串是 LocalSqlServer。

重新启动解决了这个问题。


0

除了连接字符串,你能读取任何配置设置吗?

尝试:

System.Configuration.ConfigurationManager.AppSettings("MyAppVariable");

此外,那个语法看起来有点复杂。试试这个更简单的版本:

System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接