I experienced the System.TypeInitializationException
due to a different error in my .NET framework 4 project's app.config. Thank you to pStan for getting me to look at the app.config. My configSections were properly defined. However, an undefined element within one of the sections caused the exception to be thrown.
Bottom line is that problems in the app.config can generated this very misleading TypeInitializationException
.
A more meaningful ConfigurationErrorsException
can be generated by the same error in the app.config by waiting to access the config values until you are within a method rather than at the class level of the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections.Specialized;
namespace ConfigTest
{
class Program
{
public static string machinename;
public static string hostname;
public static NameValueCollection _AppSettings;
static void Main(string[] args)
{
machinename = System.Net.Dns.GetHostName().ToLower();
hostname = "abc.com";// System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).HostName.ToLower().Replace(machinename + ".", "");
_AppSettings = ConfigurationManager.GetSection("domain/" + hostname) as System.Collections.Specialized.NameValueCollection;
}
}
}