' System.Configuration.ConfigurationErrorsException'发生在System.Configuration.dll中,已包含System.Configure

时间:2016-07-25 22:11:28

标签: c# .net visual-studio connection-string app-config

我在VS 2013中有一个Windows窗体应用程序,我正在尝试建立数据库连接。但是,每次运行程序时,都会收到以下错误:

An unhandled exception of 'System.Configuration.ConfigurationErrorsException' occurred in         
System.Configuration.dll

Additional information: Configuration system failed to initialize

这是我的文件的样子:

Program.cs

using System;
using System.Collections;
....

namespace ProgramName
{
    static class FakeNameB
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Form1.cs的

using System;
....

namespace ProgramName
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            string CS = System.Configuration.ConfigurationManager.ConnectionStrings[<nameInApp.config>].ConnectionString.ToString();

            InitializeComponent();
        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="ProgramName.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections> 
    <configurationStrings>
        <add name = <name> connectionString = "Data Source=<dataSource>;Initial Catalog=<catalog>;Integrated Security=True;" providerName="System.Data.SqlClient"></add> 
    </configurationStrings>
</configuration>

this post中的所有建议似乎都没有帮助,我无法像this post建议那样引用System.Configuration.dll。有任何想法吗?

2 个答案:

答案 0 :(得分:3)

在你的app.config中,它应该是<connectionStrings>而不是<configurationStrings>

<connectionStrings>
    <add name="[name]" connectionString="[string]" providerName="System.Data.SqlClient" /> 
</connectionStrings>

答案 1 :(得分:2)

对此特定问题的修复可以在this post的已接受答案的注释中找到,并通过将configSections标记移动到第一个子节点并将启动标记移动到最后一个部分来解决包括在内。