Reputation: 2393
I have a program called parser.exe and it uses a config file called parser.config (a txt format; I read it with streamreader). For some reasons C# complains and doesn't like this.
Unhandled Exception: System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrors
BUT if I created a file called parser.exe.config. with just followng content application runs fine:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
Why this is happening and how to suppress this problem without having parser.exe.config and changing the config name from parser.config to parser.exe.config?
Upvotes: 0
Views: 1147
Reputation: 152501
it uses a config file called parser.config (a txt format; I read it with streamreader)
There's no need for this. .NET already has a perfectly good framework for application configuration files. Just add an app.config
file to your project and Visual Studio will automatically create a parser.exe.config
file when you build.
You can then use the ConfigurationSettings.AppSettings
dictionary to read individual configuration items - or use more complex structured for more complex configurations.
To use an external configuration file for a config section, just use the configSource
attribute in app.config
:
<configuration>
<appSettings configSource="parser.config" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
parser.config
:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="Test" value="This is a test"/>
</appSettings>
why this is happening?
That's the way the framework was designed - it will look for a {executable name}.config file by default - you can add external config files as explained above but there's no way that I know of to have the framework look for a different file name by default.
You could load a new file into a separate configuration object:
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"parser.config";
var config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
But then you have to use that config
instance to access config settings:
Console.WriteLine(config.AppSettings.Settings["test"].Value);
instead of
Console.WriteLine(ConfigurationManager.AppSettings["test"]);
But that seems like a long way to go to avoid the default config file name.
Upvotes: 3
Reputation: 7783
You can tell .NET to look for your settings in another file, like this:
<configuration>
<appSettings file="parser.config"></appSettings>
</configuration>
Upvotes: 1