I wrote the following code to get ConfigurationManager data, to update it:
private static void UpdateConfigurationFile()
{
#if DEBUG
string applicationName =
Environment.GetCommandLineArgs()[0];
#else
string applicationName =
Environment.GetCommandLineArgs()[0]+ ".exe";
#endif
string exePath = System.IO.Path.Combine(
Environment.CurrentDirectory, applicationName);
// Get the configuration file. The file name has
// this format appname.exe.config.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(exePath);
string server = ConfigurationManager.AppSettings["server"];
}
At the end of the code, server is null.
The XML has the corresponding server code:
<applicationSettings>
<forLiDAR.Properties.Settings>
<setting name="Server" serializeAs="String">
<value>localhost</value>
</setting>
What am I doing wrong?
Ok, I have a solution to your problem.
Not easy to explain as it is not really your fault, VS has a bug that is being dragged with it for years now.
So lets take it step-by-step:
If we follow the documentation, all we have to do is:
No need to OpenExeConfigration or anything else , just those two lines! and .NET like a charm should be able to save the new setting into the configuration file.. except that it don't :) Instead it shouts 'Configuration System failed to initialize'!!
So.. we think "alright, they didn't cover it all in documentation.. lets add what we think is missing.." and so we add:
And we will get ... another exception - null reference this time. So we ask - "what is going there?!" and from debug we add watch for 'config.AppSettings.Settings' and to our horror we see that .NET actually trying to tell us "There is no spoon.." (or settings count is 0)
So at this point we can conclude this crap is definitely not working with application that use AppConfig.. but it might work with applications that use WebConfig - I didn't test that. (oh, just to make it clear:'This crap' means adding settings file by using the right-click on the project menu and going to settings tab)
So I did that too and tested the following lines:
This worked - but I need to tell you that the 'Scope' has to be 'user' and not Application.. if its 'application' the setting will not have a setter.. and where did it save the information? in the AppData folder for that user.. which is logical.
This of course means that in order to check manually while you debug what was saved you need to go the configuration file of your app which resides in the AppData folder and not in your debug/bin folder.
So, last I will try to show you how your app should look like:
And provided you add Settings1.Settings file as I mentioned, this is how appConfig could look like:
As requested in the comment here is a link to the bug report:
Configuration in the App.Config and ApplicationSettings