253

I'm currently creating a Login form and have this code:

string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
try
{
    using (OdbcConnection connect = new OdbcConnection(connectionString))
    {
        connect.Open();
        OdbcCommand cmd = new OdbcCommand("SELECT username, password FROM receptionist", connect);
        OdbcDataReader reader = cmd.ExecuteReader();

        if (username_login.Text == username && password_login.Text == password)
        {
            this.Hide();
            MessageBox.Show("Invalid User", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            this.Close();
        }
        else 
            MessageBox.Show("Invalid User", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        connect.Close();
    }
}
catch (OdbcException ex)
{
    MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

But whenever I try to type in the username and password there is an error called "Configuration system failed to initialize". What kind of problem is this, and how could I solve this?

3

28 Answers 28

422

Make sure that your config file (web.config if web, or app.config if windows) in your project starts as:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" 
                      type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

            <section name="YourProjectName.Properties.Settings" 
                     type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
                     requirePermission="false" />

        </sectionGroup>
    </configSections>
</configuration>

Note that inside the configuration element, the first child must be the configSections element.

In the name property on section element, make sure you replace YourProjectName with your actual project's name.

It happened to me that I created a webservice in a class library project, then I copied (overwriting) the config file (in order to bring the endpoints configuration) to my windows app and I started to have the same problem. I had inadvertently removed configSections.

11
  • 87
    "inside the 'configuration' element, the first child must be the 'configSections' element" << this was the crucial point for me. Thanks. Dec 19, 2011 at 17:41
  • 9
    Just another scenario - If you are looking for ConfigurationManager.Appsettings[""], make sure that the <appSettings> is present in the config. Otherwise you will get this exception
    – LCJ
    Feb 19, 2013 at 7:46
  • 7
    It fixed my problem where configSections element existed but located later part of the app.config. I can't help asking why this error happened. I thought XML elements don't need to be ordered. Jul 28, 2013 at 22:25
  • 4
    This is correct. The configSections should be the first child node under, configuration element. Apr 13, 2016 at 10:04
  • 9
    The way Microsoft implemented this app.config is retarded!!! The least they could do is throw a better error message! Jun 20, 2017 at 15:02
124

Delete old configuration files from c:\Users\username\AppData\Local\appname and c:\Users\username\AppData\Roaming\appname and then try to restart your application.

10
  • 2
    Thanks, working. But I still don't understand what is problem?
    – liquide
    Apr 24, 2014 at 13:26
  • 1
    under the local folder user.config file was blank. After deleting local folder app start working
    – Ozgur
    Jul 25, 2014 at 17:21
  • 3
    Thanks it worked. But what could be the reason for this error.
    – vasuy19
    Jan 6, 2015 at 11:29
  • 1
    My file was filled with low-values (0x00). I copied a working one in and then it was fine
    – DanW
    Dec 7, 2015 at 0:12
  • 1
    My config file in this location was corrupted during a power outage event - the config file which is normally XML was filled with NUL bytes
    – mroselli
    Dec 21, 2016 at 18:45
20

Sometimes the Error occurs because a windows create a duplicate in the

C:\Users\App Data\Local\"You App Name"...

Just delete this folder and done. try it.

1
  • 2
    THANK YOU. I was unable to fix my issue with settings file strings not being "picked up" by my application. I cleaned out the config files, regenerated the .suo file, deleted all existing .settings files and was still unable to load from any new settings file, but did not receive any errors on build. This nightmare has finally come to an end.
    – Rachael
    Apr 7, 2016 at 23:51
15

If you've added your own custom configuration sections to your App.Config, make sure you have defined the section in the <configSections> element. I added the my config XML but forgot to declare the configuration section up top - which caused the exception "Configuration system failed to initialize" for me.

3
  • 3
    Also - if you have a section declared up top and the name in the section below has a typo, you will get this error. If you look at the InnerException of the thrown exception, it will tell you which section is the problem.
    – shindigo
    Jan 20, 2014 at 17:02
  • That innerException that @shindigo mentioned will also tell you WHERE the offending file is. In my project it's nowhere near the User's App Data, but rather at [project_path]\bin\Debug\net5.0-windows\MVVM Playground.dll.config. Deleting it made the error of an improperly defined section go away, but then the application couldn't find any data. I had to manually copy my App.config into that file. Jun 24, 2022 at 22:16
  • I additionally discovered that App.config can be set to always "Copy if newer" when running the debugger: Click on the file in the Solution Explorer and additional properties appear that aren't available when simply viewing the file. Change property Copy to Output Directory to Copy if newer. Jun 24, 2022 at 22:43
9

After a long search I realised, this exception has an inner exception that tells you exactly what is wrong with your config file

1
  • 1
    I was trying to comment-uncomment different sections of my app.config and on exception didn't even look on inner exception. And after seeing this answer I found what was the issue. Thanks.
    – Sid
    Jun 26, 2020 at 3:54
6

I had this same problem with an MSTest class: Marlon Grech in his article says "the element has to be defined as the first element in the App.config."

So make sure that is the first element in under the element. I had put AppSettings first.

1
  • ohh .. my bad: you indeed did but I didn't notice ;-) Thanks for the clarification
    – kleopatra
    Aug 29, 2013 at 7:16
5

If you have User scoped settings you may also have a user.config file somewhere in the [Userfolder]\AppData\Local\[ProjectName] folder.

If you later remove the User scoped settings the user.config will not automatically be removed, and it's presence may cause the same error message. Deleting the folder did the trick for me.

4

I know this has already been answered but I had exactly the same problem in my unit tests. I was tearing my hair out - adding an appSettings section, and then declaring the configuration section as per the answer. Finally found out that I had already declared an appSettings section further up my config file. Both sections pointed to my external settings file "appSettings.config" but the first appSettings element using the attribute file whilst the other used the attribute configSource. I know the question was about the connectionStrings. Sure enough, this happens if the appSettings element is the connectionStrings element being duplicated with different attributes.

Hopefully, this can provide someone else with the solution before they go down the path I did which leads to wasting an hour or two. sigh oh the life of us developers. We waste more hours some days debugging than we spend developing!

1
  • Bingo. Had appSettings and applicationSettings both.
    – SushiGuy
    Jul 13, 2018 at 21:46
3

I started to get this problem after uninstalling Oracle Client Drivers and it removed my C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\machine.config!

Copying it from another computer resolved the problem.

3
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="xyz" value="123" />    
  </appSettings>
</configuration>
0
2

Easy solution for .Net Core WinForms / WPF / .Net Standard Class Library projects

step 1: Install System.Configuration.ConfigurationManager by Nuget Manager

step 2: Add a new App.Config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Bodrum" value="Yalikavak" />    
  </appSettings>
</configuration>

step3: Get the value

string value = ConfigurationManager.AppSettings.Get("Bodrum");
// value is Yalikavak

If you are calling it from a Class Library then add the App.Config file on your Main Project.

1

Wow it took me forever to figure out this one. For some reason changing the attribute [assembly: AssemblyCompany("CompanyName")] at AssemblyInfo.cs made this error disappear. I was referencing a project that had a different value for the attribute [assembly: AssemblyCompany("CompanyName")]. I maked sure both projects had the same attribute value and it worked great!

1
  • Is this a bug? One can hardly be expected to make your company name match a third party project you happen to reference. May 5, 2014 at 15:09
1

Same problem with me I solved my problem by removing verion="v3.5" from App.config.

Before

 <?xml version="1.0" encoding="utf-8"?>
  <configuration>

  <startup>

 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
 </startup>
 <supportedRuntime version="v3.5" />//Remove this
</configuration>

Solution

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <startup>

    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
  </startup>
  </configuration>

Here is how to use version on

MSDN Support Runtime Element

1

I solved the problem by using the below code

   <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings"
                  type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

      <section name="YourProjectName.Properties.Settings"
               type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
               requirePermission="false" />

    </sectionGroup>

  </configSections>
  <appSettings>
    <add key="SPUserName" value="TestUser" />
    <add key="SPPassword" value="UserPWD" />
  </appSettings>
</configuration>
0

It is worth noting that if you add things like connection strings into the app.config, that if you add items outside of the defined config sections, that it will not immediately complain, but when you try and access it, that you may then get the above errors.

Collapse all major sections and make sure there are no items outside the defined ones. Obvious, when you have actually spotted it.

0

In my case the only solution was to add the reference to the System.Configuration in my Test project as well.

0

This is kinda dumb, but for me I fixed it by doing a get latest from source control on my code. I think there was some new configuration element that was added by someone else, and I needed to overwrite my configuration files. OP shows the error I had gotten, which wasn't really pointing me in the right direction.

0

I too faced the same problem, But accidentally i written the without writting the ,the previous one should go inside this tags. thus the 'Configuration System Failed to Initialize' error was arising. Hope it will help

0

In My case, I have two configsections in the app.config file. After deleting the one hiding in the code lines, the app works fine.

So for someone has the same issue, check if you have duplicate configsections first.

0

If you are dealing with an Azure WebJob - I had to remove the following after upgrading to the latest 4.6.1.

  <compilation debug="true" targetFramework="4.6.1">
    <assemblies>
      <add assembly="System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    </assemblies>
  </compilation>

Hope this helps.

0

In my case, within my .edmx file I had run the 'Update Model From Database' command. This command added an unnecessary connection string to my app.config file. I deleted that connection string and all was good again.

0

Try to save the .config file as utf-8 if you have some "special" characters in there. That was the issue in my case of a console application.

0

As @Flash Gordon mentioned in his comment, you will need to define any custom tag (as a section) in your App.config file, under <configSections>. For example, you're working on a test automation project with SpecFlow & adding <specFlow> tag, then a simplest version of App.config will look like this: enter image description here

0

I just had this and it was because I had a <configuration> element nested inside of a <configuration> element.

0

I restarted Visual studio and even the whole PC. I cleaned the project, rebuild, and deleted bin file.

Nothing helped until i changed the configuration from x64 to x86. It worked on x86 but when i changed it back it also worked!

0

I tried all of the solutions above trying to figure out why one of my unit tests were failing to pick up the configuration from an app.config file that is perfect.

I had 2 references to the same assembly like so:

duplicate reference

project file before and after

Removing the (duplicate) reference in yellow fixed it for me.

I hope this works for someone else, it drove me nuts for a while.

0

If you have a custom section, you need to mention that under configSections right below configurations tag.

Please check your transform files, make sure you remove the unnecessary tags.only the section that are going to vary needs to be there in transform files. dont mention config section in the transform files if not needed. this would also cause the problem.

if you have any syntax error in machine.config, then also this error is expected.

0

I was also getting

'System.Configuration.ConfigurationErrorsException' in System.Configuration.dll

If you have windows check the slashes / I was working with a project from a guy working in linux, so he had inverted them.

Not the answer you're looking for? Browse other questions tagged or ask your own question.